Nil-coalescing to provide default values ​​in Swift 1.2

Earlier (i.e. before Swift 1.2) I used this code:

self.name = jsonDictionary["name"] as? String ?? "default name string here"

I found this to be a readable but concise way:

  • getting value from dictionary
  • check its type that i expect
  • default value assignment

However, in Swift 1.2, I get this compiler error:

Consecutive statements on a line must be separated by ';'

I don't see anything in the Xcode 6.3 release notes or the Apple Swift blog post about this.

+4
source share
1 answer

Now you need to use parentheses:

self.name = (jsonDictionary["name"] as? String) ?? "default name string here"
+5
source

All Articles