我在获取所有词典键时遇到问题
当我拨打.keys
时,我收到如下错误
而且我不知道如何解决它
感谢。
错误:
Value of optional type 'LazyMapCollection<Dictionary<String, ChatroomMember>, String>?' not unwrapped; did you mean to use '!' or '?'?
class Chatroom:Model {
var id:String = ""
var members:[String:ChatroomMember] = [String:ChatroomMember]()
}
class ChatroomMember:Model {
var id:String = ""
}
class ViewController: UIViewController {
weak var chatroom:Chatroom?
override func viewDidLoad() {
var memberUsers:[String] = [String](chatroom?.members.keys) // get Error
}
}
答案 0 :(得分:0)
只需打开您的chatroom
:
var memberUsers:[String] = [String](chatroom!.members.keys)
或者(如果chatroom
有机会保持未初始化状态)使用可选if let
解包:
var memberUsers:[String]
if let chatroom = chatroom {
memberUsers = Array(chatroom.members.keys)
} else {
memberUsers = []
}
或者,如果您的整个应用依赖于chatroom
的存在,请保护它:
guard let chatroom = self.chatroom else {
// chatroom is not here!
return
}
var memberUsers = Array(chatroom.members.keys)
P.S。您可以依赖Swift类型推断并使用Array(..)
代替[String](..)
将惰性keys
集合转换为普通数组。