xcode 不能强制解包非可选类型的值:避免“Optional()”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33785303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot force unwrap value of non-optional type: Avoid "Optional()"
提问by Nicklas Mandrup Frederiksen
I've saved player skills in NSUserDefaults as a dictionary but when I want to access it, xcode says "cannot force unwrap value of non-optional type". When I remove "!" it writes out "Optional (1)" where I want to get rid of "Optional()". How can I just write out "1"?
我已经将 NSUserDefaults 中的玩家技能保存为字典,但是当我想访问它时,xcode 说“无法强制解包非可选类型的值”。当我删除“!” 它写出“可选(1)”,我想去掉“可选()”。我怎么能写出“1”?
if let playerDic = defaults.objectForKey("Player") as? [String: Int] {
lbLevel.setText(String(playerDic!["level"]))
}
turns into
变成
"Cannot force unwrap value of non-optional type"
where
在哪里
if let playerDic = defaults.objectForKey("Player") as? [String: Int] {
lbLevel.setText(String(playerDic["level"]))
}
turns into
变成
Optional(1)
采纳答案by Mr Beardsley
You've already unwrapped playerDic in the if let binding. Just drop the force unwrap like the error message tells you.
您已经在 if let 绑定中解开 playerDic 。就像错误消息告诉您的那样,只需放下强制展开即可。
if let playerDic = defaults.objectForKey("Player") as? [String: Int] {
lbLevel.setText(String(playerDic["level"]))
}
UpdateSorry just saw your update. So playerDic isn't an optional, but the values returned for keys are optionals. If you ask for the value for a key that is not in the dictionary you will get an optional with the value of nil.
更新抱歉刚刚看到您的更新。所以 playerDic 不是可选的,但为键返回的值是可选的。如果您要求字典中没有的键的值,您将获得一个值为 nil 的可选项。
if let
playerDic = defaults.objectForKey("Player") as? [String: Int],
level = playerDic["level"] {
lbLevel.setText("\(level)")
}
Here you can bind multiple values in a single if let. Also, you can use String(level) or use string interpolation "(level)" depending on what you prefer.
在这里,您可以在单个 if let 中绑定多个值。此外,您可以根据自己的喜好使用 String(level) 或使用字符串插值“(level)”。
回答by Pedro Trujillo
The bang at the end (!) :
最后的爆炸(!):
You are trying to pass an optional to a method that does not receive nil
: String(optional)
to solve this just unwrap it with (!) at the end String(optional!)
:
您正在尝试将一个可选项传递给一个没有接收到的方法nil
:String(optional)
要解决这个问题,只需在最后用 (!) 解开它String(optional!)
:
if let playerDic = defaults.objectForKey("Player") as? [String: Int] {
lbLevel.setText(String(playerDic["level"]!)) <-- the bang at the end
}