ios - Swift : value of optional type '[Int : Int]?' not unwrapped; did you mean to use '!' or '?' ? 问题

标签 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 被定义为类中的全局变量。

如有任何指点,我们将不胜感激。

最佳答案

因为字典查找返回一个可选的(键可能丢失),你需要解包 next[storyIndex] 的结果,然后才能索引它。在此处使用 ?(可选链接)来安全地解包值。由于您需要结果,而不是与 nil 进行比较,请使用 if let(可选绑定(bind)):

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

如果 storyIndex 不是有效键,则 next[storyIndex] 将为 nil,可选链的结果将为。如果 myTag 不是有效键,结果也将为 nil。在两个键都有效的情况下,可选链的结果将为 Int? 并且 nextStory 将绑定(bind)到展开的值。


如果您有一个默认值用于 storyIndex(例如 1),如果查找失败,您可以使用 nil 合并运算符 ?? 还可以使用可选链在一行中完成此操作:

storyIndex = next[storyIndex]?[myTag] ?? 1

或者(为了查找失败而保留 storyIndex 不变):

storyIndex = next[storyIndex]?[myTag] ?? storyIndex

关于ios - Swift : value of optional type '[Int : Int]?' not unwrapped; did you mean to use '!' or '?' ? 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51580530/

相关文章:

ios - 在 imageview 中加载来自互联网的图像的函数

ios - 我们可以让 2 个具有相同 bundle id 的 ios 应用程序针对不同的 ios 吗?

C# 是否清除具有值类型的 List<T> 仍然是 O(n) 操作?

ios - X 单元格后 UITableViewCells 停止正确显示

ios - NSInternalInconsistencyException 原因 : 'Invalid update: invalid number of rows in section 0'

ios - 如何从另一个 Controller 引发事件。

php - 将每一行读入数组

iphone - 图片放入数组 ios开发

ios - swift : Segue Taped menu item's name on navigation bar title with SWRevealViewController

ios - 从 JSON 中快速解析多个图像