greenoldman
greenoldman

Reputation: 21062

Can Swift optional be nested?

I cannot find the answer to this question, for example can I have optional of an optional of a String? I tried to write a small test to check it out:

let a : String? = nil;
let b : String?? = a;
if b!=nil { // error
  println("has value");
}
else {
  println("fail");
}

but since I am not a Swift programmer I don't know what to do with error saying "cannot assign to the result of this expression".

Upvotes: 1

Views: 272

Answers (1)

Tommy
Tommy

Reputation: 100622

Yes you can; your syntax is incorrect though. This line:

if b!=nil

Is digested by the compiler as:

if (b!) = nil

... so it thinks you're trying to assign nil to the unwrapped optional. Swift doesn't allow you to make assignments within if statements (in contrast to Objective-C). Instead be clearer:

if b != nil

EDIT: and, to finish the thought, proving that the syntactic sugar really is making an optional optional, if you add:

if let b = b {
    print("\(b)")
}

You should see nil as the printed output.

Upvotes: 2

Related Questions