Is it possible to match patterns with options in Swift?

I don't like if letoptions syntax too much , and I'm trying to figure out if I can get pattern matching to work. I am trying to use the following code on a playground, but I do not see any output in the statements println. What am I doing wrong?

let one:Int? = 1

switch one {
case .Some(let numeral):
    println("Caught a \(numeral)")
default:
    println("Nothing to catch")
}
+4
source share
3 answers

A little out of context, but: Playground does not print statements println()in the right column. You can again write the variable you want to read:

...
case .Some(let numeral):
    println("Caught a \(numeral)")
    numeral
...

In this case you will see {Some 2}.

Or you can open the assistant editor (View → Assistant Editor → Show Assistant Editor) and read Console outputto read the rated println().

EDIT Xcode 6 beta-5

Xcode 6 beta-5 , , println(), .

+5

, (_) .

+1

A more concise way to do what you want in your example is to use if case let rather than switch.

if case let numeral? = one {
  print("Caught a \(numeral)")
}

or

if case .Some(let numeral) = one {
  print("Caught a \(numeral)")
}

Requires Swift 2.0

+1
source

Source: https://habr.com/ru/post/1543543/


All Articles