代码之家  ›  专栏  ›  技术社区  ›  Simon R

Swift的问题:可选类型'[Int:Int]'的值没有打开包装;你是不是想用'!'或'?'?

  •  0
  • Simon R  · 技术社区  · 8 年前

    我正在学习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 回复  |  直到 8 年前
        1
  •  6
  •   vacawama    8 年前

    因为字典查找返回一个可选的(键可能丢失),所以需要打开 next[storyIndex] 在你索引它之前。使用 ? ( 可选链接 )在这里安全地展开值。因为你需要结果,而不是比较 nil ,使用 if let ( 可选绑定 ):

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

    如果 storyIndex 不是有效的密钥,则 下一个[故事索引] ,可选链的结果将是 . 如果 myTag 不是有效的密钥,结果也将是 . 如果两个键都有效,则可选链的结果将是 Int? nextStory 将绑定到未包装的值。


    如果有默认值可用于 故事索引 (例如 1 )如果查找失败,可以使用 零凝聚算子 ?? 还有 可选链条 要在一行中执行此操作:

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

    或(离开 故事索引 查找失败时保持不变):

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