Swift 参数类型';Int';不符合预期的类型';NSCoding&;NSCopying&;NSObjectProtocol';
我是Swift新手,正在尝试一些教程来学习和完善我在Swift上的知识。我在这段代码中偶然发现了我不理解的上述错误。如果你们中有人有想法,请解释一下这里出了什么问题Swift 参数类型';Int';不符合预期的类型';NSCoding&;NSCopying&;NSObjectProtocol';,swift,researchkit,Swift,Researchkit,我是Swift新手,正在尝试一些教程来学习和完善我在Swift上的知识。我在这段代码中偶然发现了我不理解的上述错误。如果你们中有人有想法,请解释一下这里出了什么问题 let textChoices = [ ORKTextChoice(text: "Create a ResearchKit app", value:0), ORKTextChoice(text: "Seek the Holy grail", value:1), ORKTextChoice(text
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)
]
我从中得到了另一个解决方案。虽然有效,但我仍然不清楚问题和解决方案。我缺少的概念是什么。由于
ORKTextChoice
的初始化器有一个值的抽象参数类型:
,Swift将回退,将传递给它的整数文本解释为Int
——这不符合NSCoding
、NSCopying
或NSObjectProtocol
。它是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对应项。然而,据报道,情况已不再如此。您需要使用作为
使桥显式