【问题标题】:Argument type 'Int' does not conform to expected type 'NSCoding & NSCopying & NSObjectProtocol'参数类型“Int”不符合预期类型“NSCoding & NSCopying & NSObjectProtocol”
【发布时间】:2016-10-07 10:31:23
【问题描述】:

我是 Swift 新手,正在尝试一些教程来学习和完善我对 Swift 的了解。我在这段代码中偶然发现了我不理解的上述错误。如果你们中的任何人有想法,请在此处解释问题所在。

    let textChoices =   [
    ORKTextChoice(text: "Create a ResearchKit app", value:0),
    ORKTextChoice(text: "Seek the Holy grail", value:1),
    ORKTextChoice(text: "Find a shrubbery", value:2)
]

我通过 Xcode 提供的建议解决了错误,现在我的代码看起来像

    let textChoices =   [
    ORKTextChoice(text: "Create a ResearchKit app", value:0 as NSCoding & NSCopying & NSObjectProtocol),
    ORKTextChoice(text: "Seek the Holy grail", value:1 as NSCoding & NSCopying & NSObjectProtocol),
    ORKTextChoice(text: "Find a shrubbery", value:2 as NSCoding & NSCopying & NSObjectProtocol)
]

我从answer 得到了另一个解决方案。虽然它有效,但我仍然不清楚问题和解决方案。我缺少什么概念。

【问题讨论】:

    标签: swift researchkit


    【解决方案1】:

    由于ORKTextChoice 的初始化程序有一个value: 的抽象参数类型,Swift 将回退将传递给它的整数文字解释为Int——这不符合NSCoding、NSCopying 或@ 987654327@。它是 Objective-C 的对应物,NSNumber,但是确实如此。

    虽然,不是强制转换为NSCoding & NSCopying & NSObjectProtocol,这会导致到NSNumber 的桥接(尽管是间接且不清楚的),但您可以直接建立这个桥接:

    let textChoices = [
        ORKTextChoice(text: "Create a ResearchKit app", value: 0 as NSNumber),
        ORKTextChoice(text: "Seek the Holy grail", value: 1 as NSNumber),
        ORKTextChoice(text: "Find a shrubbery", value: 2 as NSNumber)
    ]
    

    您的原始代码在 Swift 3 之前可以工作,因为 Swift 类型能够隐式桥接到它们的 Objective-C 对应项。但是,根据SE-0072: Fully eliminate implicit bridging conversions from Swift,情况不再如此。您需要使用as 明确桥接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多