不能强制解包非可选类型的值:避免“Optional()"; [英] Cannot force unwrap value of non-optional type: Avoid "Optional()"

查看:41
本文介绍了不能强制解包非可选类型的值:避免“Optional()";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 NSUserDefaults 中的玩家技能保存为字典,但是当我想访问它时,xcode 说无法强制解开非可选类型的值".当我删除!"它写出可选(1)",我想去掉可选()".我怎么能只写出1"?

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"?

if let playerDic = defaults.objectForKey("Player") as? [String: Int] {
    lbLevel.setText(String(playerDic!["level"]))
}

变成

"Cannot force unwrap value of non-optional type"

哪里

if let playerDic = defaults.objectForKey("Player") as? [String: Int] {
    lbLevel.setText(String(playerDic["level"]))
}

变成

Optional(1)

推荐答案

您已经在 if let 绑定中解包了 playerDic.只需像错误消息告诉您的那样取消强制展开即可.

You've already unwrapped playerDic in the if let binding. Just drop the force unwrap like the error message tells you.

if let playerDic = defaults.objectForKey("Player") as? [String: Int] {
    lbLevel.setText(String(playerDic["level"]))
}

更新抱歉刚刚看到你的更新.所以 playerDic 不是可选的,但为键返回的值是可选的.如果您要求字典中没有的键的值,您将得到一个值为 nil 的可选项.

Update Sorry 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.

if let 
      playerDic = defaults.objectForKey("Player") as? [String: Int],
      level = playerDic["level"]   {
    lbLevel.setText("\(level)")
}

在这里你可以在一个 if let 中绑定多个值.此外,您可以根据自己的喜好使用 String(level) 或使用字符串插值(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.

这篇关于不能强制解包非可选类型的值:避免“Optional()";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆