如何获取所有字典键(' LazyMapCollection< ..>'错误)

时间:2017-10-31 07:58:36

标签: ios arrays swift dictionary

我在获取所有词典键时遇到问题 当我拨打.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    

    }

}

1 个答案:

答案 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集合转换为普通数组。