user1007522 user1007522 - 1 year ago 77
iOS Question

Dictionary has optional key

I'm having a array of

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.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
or some other letter of course. But why is it optional? The key in the forloop is not optional so how does this come?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download