【问题标题】:How to declare an empty array of type 'CNLabeledValue' using Swift 3?如何使用 Swift 3 声明一个“CNLabeledValue”类型的空数组?
【发布时间】:2017-02-01 20:06:37
【问题描述】:

以前在 iOS 9 中工作的代码是:

var valuesArray : [CNLabeledValue] = []

但我不知道如何在 Swift 3 中做到这一点。

【问题讨论】:

  • CNLabeledValue 是 Swift 3 中的一个泛型类,所以你不能有 CNLabeledValue 类型的东西——它必须是 CNLabeledValue<Something>。它是哪个“东西”取决于您对这个数组所做的事情,因此如果没有更全面地了解您的数组的使用方式,我们将无法提供更多帮助。
  • 我正在使用 Contacts Framework,CNPhoneNumber 数组也是如此。
  • 'var valuesArray : [CNLabeledValue] = []' 解决问题。

标签: ios swift3 contacts-framework


【解决方案1】:

这是解决方案:

var phoneNumbers : [CNLabeledValue<CNPhoneNumber>] = []

正如 OOPer 在this post 中指出的那样:

CNLabeledValue 的泛型参数声明为&lt;ValueType : NSCopying, NSSecureCoding&gt;。因此,在这种情况下,您可以选择符合NSCopyingNSSecureCoding 的任何类型。 NSString 有,String 没有。

【讨论】:

  • 所引用的句子可能会导致您对案件的一些误解。您可能需要为ValueType 选择一种合适的类型——在您的情况下,它是CNPhoneNumber。 “任何类型”部分不适用于您的问题。
【解决方案2】:

类似这样(以填写电话号码为例):

            let phonesArray : [Phones] = phones!
            var phonesToAdd = [CNLabeledValue]()
            for phone in phonesArray
            {
                if let phoneT = phone.phoneType
                {
                    if phoneT.lowercaseString == "mobile"
                    {
                        let mobilePhone = CNLabeledValue(label: "mobile",value: CNPhoneNumber(stringValue: phone.phone))
                        phonesToAdd.append(mobilePhone)
                    }
                    if phoneT.lowercaseString == "landline"
                    {
                        let landlinePhone = CNLabeledValue(label: "landline",value: CNPhoneNumber(stringValue: phone.phone))
                        phonesToAdd.append(landlinePhone)
                    }
                }
            }
            contactData.phoneNumbers = phonesToAdd

【讨论】:

  • OP 指定 Swift 3,您的代码似乎是用 Swift 2 编写的。
  • 好的,如果是 swift 3,写这样的东西是有意义的 [CNLabeledValue]()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-29
相关资源
最近更新 更多