我目前正在学习 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/