Swift问题:可选类型'[Int:Int]的值?'不展开你是说用'!'要么 '?'?

时间:2018-07-29 12:55:20

标签: ios arrays swift

我目前正在学习Swift,并且我正在尝试创建一个函数,该函数将根据按下的按钮来更新故事。我已经设置了按钮按下位,但随后将按钮的标记传递给了updateStory函数。

func updateStory(myTag: Int) {

    let next = [
        1 : [
            1 : 3,
            2 : 2,
        ],
        2 : [
            1 : 3,
            2 : 4,
        ],
        3 : [
            1 : 6,
            2 : 5,
        ]
    ]

    // Error:(86, 17) value of optional type '[Int : Int]?' not unwrapped; did you mean to use '!' or '?'?
    if (next[storyIndex][myTag] != nil) {
        let nextStory = next[storyIndex][myTag]
        storyIndex = nextStory
    }

}

StoryIndex被定义为类中的全局变量。

任何指针将不胜感激。

1 个答案:

答案 0 :(得分:6)

由于字典查找返回一个可选(键可能会丢失),因此您需要先对next[storyIndex]的结果进行包装,然后才能为其建立索引。在此处使用?可选链接)可以安全地解包该值。因为您需要结果,所以不要将其与nil进行比较,而应使用if let可选绑定):

if let nextStory = next[storyIndex]?[myTag] {
    storyIndex = nextStory
}

如果storyIndex不是有效的密钥,则next[storyIndex]将是nil,可选链的结果将是nil。如果myTag不是有效的密钥,则结果也将是nil。如果两个键均有效,则可选链的结果将为Int?,并且nextStory将绑定到未包装的值。


如果查找失败,则具有storyIndex的默认值(例如1),则可以使用 nil合并运算符 {{1} }和可选链一起在一行中完成此操作:

??

或(对于查找失败,保留storyIndex = next[storyIndex]?[myTag] ?? 1 不变):

storyIndex