本文介绍了字典有可选键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 CNContact 数组,我用这个函数对它们进行排序:

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()

contactDictionary 的类型:

Where contactDictionary is of type:

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

现在,当我看到 contactDictionary 当它被填满时它可以工作,除了键总是 Optional(\"T"\") 或其他一些字母当然.但为什么它是可选的吗?forloop 中的键不是可选的,这是怎么来的?

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?

推荐答案

firstCollection 属性是可选类型,所以你可能在这里得到可选 contactName.characters.first,如果您使用 if letguard 包装它,将解决您的问题.

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
}

这篇关于字典有可选键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 00:02