Dictionary has optional key

那年仲夏 提交于 2019-12-13 07:15:17

问题


I'm having a array of CNContact and I sort them with this function:

for contact in self.contacts {

   var contactName = contact.organizationName

    let key: String = String(contactName.characters.first).uppercaseString
    if let arrayForLetter = self.contactDictionary[key] {
        self.contactDictionary[key]!.append(contact)
        self.contactDictionary.updateValue(arrayForLetter, forKey: key)
    } else {
        self.contactDictionary.updateValue([contact], forKey: key)
    }
}

self.keys = self.contactDictionary.keys.sort()

Where contactDictionary is of type:

var contactDictionary: [String: [CNContact]] = [String: [CNContact]]()
var keys: [String] = []

Now when I see the contactDictionary when it's filled it works except the key always Optional(\"T"\") or some other letter of course. But why is it optional? The key in the forloop is not optional so how does this come?


回答1:


first property of Collection is of optional type, So you are getting optional probably here contactName.characters.first, if you wrapped it using if let or guard will solved your issue.

if let fc = name.characters.first {
    let key = String(fc).uppercaseString
}



回答2:


Try to do it this way:

for contact in self.contacts {
   var contactName = contact.organizationName

    if let key = String(contactName.characters.first).uppercaseString {
        if let arrayForLetter = self.contactDictionary[key] {
            self.contactDictionary[key]!.append(contact)
            self.contactDictionary.updateValue(arrayForLetter, forKey: key)
        } else {
            self.contactDictionary.updateValue([contact], forKey: key)
        }
    }
}

self.keys = self.contactDictionary.keys.sort()


来源:https://stackoverflow.com/questions/40691943/dictionary-has-optional-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!