An optional dictionary type gives the value "Value of an optional type not expanded"

Why is this:

let optionalInts: [Int: Int?] = [ 0: 0 ] let regularInt: Int = optionalInts[0]! 

Give me this compile time error:

Error: value of optional type 'Int?' does not unfold; you wanted to use '!' or '?'?

But it works:

 let optionalInts: [Int: Int?] = [ 0: 0 ] let regularInt: Int = optionalInts[0]!! // <-- notice the double "!!" 
0
ios swift
Apr 17 '15 at 6:36
source share
1 answer

This is a bit confusing, but the value in the Dictionary already optional, so the value is optional:

 let optionalInts: [Int: Int?] = [ 0: 0 ] 

Is redundant, making a double-optional value similar to:

 let doubleOptionalInt: Optional<Optional<Int>> = 0 

So what you need to do is discard the option:

 let optionalInts: [Int: Int] = [ 0: 0 ] 

Perhaps (or maybe not) surprisingly, you can recursively specify options unlimitedly:

 let wayTooManyOptionalsInt: Int?????????????? = 0 

And it will take the same amount ! to deploy it back to Int :

 let backToInt: Int = wayTooManyOptionalsInt!!!!!!!!!!!!!! 
0
Apr 17 '15 at 6:36
source share



All Articles