可选类型字典产生“未包装的可选类型的值”

时间:2015-04-17 06:36:44

标签: ios swift

为什么这样:

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

给我这个编译时错误:

  

错误:可选类型'Int?'的值没有打开;你的意思是用'!'还是'?'?

但这有效:

let optionalInts: [Int: Int?] = [ 0: 0 ]
let regularInt: Int = optionalInts[0]!! // <-- notice the double "!!"

1 个答案:

答案 0 :(得分:0)

这有点令人困惑,但Dictionary中的值已经是可选的,因此将值设为可选:

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

是多余的,使值成为双重可选,类似于:

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

所以你需要做的就是删除可选项:

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

可能(或许不是)令人惊讶的是,你可以无限期地递归地选择选项:

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

并且需要相同数量的!才能将其展开回Int

let backToInt: Int = wayTooManyOptionalsInt!!!!!!!!!!!!!!