0

I have the following piece of code, in a xcode playground.

I'm using xcode 8.2.1 and swift 3.0.2

The comments on the code are the outputs in the playground.

var foo:String! = "foo" //"foo"
var bar:String? = "bar" //"bar"
let text = "text val = " + foo //"text val = foo"
let text2 = "text2 val = \(foo) " //"text2 val = Optional("foo") "
let text3 = "text3 val = " + bar! //"text3 val = bar"
let text4 = "text4 val = \(bar) " //"text4 val = Optional("bar") "

I can't understand why when i use \(foo) and \(bar) to concatenate the optional into the string, the behavior of the optional is the same, when foo is a implicitly unwrapped optional and bar is not. Shouldn't the output for:

let text2 = "text2 val = \(foo) "

Be

"text2 val = foo "

Can someone explain why the expression \(foo) isn't unwrapping?

  • Why should `\(foo)` unwrap? `"\(nil)"` will print `nil`. – kennytm Apr 14 '17 at 17:07
  • `foo` is implicitly unwrapped optional but it's still an optional. If it can be converted to normal optional instead of unwrapping, it will be. Just use `\(foo!)` and avoid implicitly unwrapped optionals when possible. – Sulthan Apr 14 '17 at 17:07
  • Here's a really good post on implicitly unwrapped optionals: https://krakendev.io/when-to-use-implicitly-unwrapped-optionals/ – toddg Apr 14 '17 at 17:47

0 Answers0