2016-10-07 56 views
4

我是Swift的新手,正在尝试一些教程来学习并在Swift上磨练我的知识。我偶然发现了这个我不明白的代码中的错误。如果你们中的任何人有想法,请在此解释最新情况。参数类型'Int'不符合期望的类型'NSCoding&NSCopying&NSObjectProtocol'

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了。虽然它有效,但我仍然不清楚问题和解决方案。我错过了什么概念。

回答

5

作为ORKTextChoice的初始化剂有一个抽象参数类型value:,SWIFT将回退到上解释传递给它的Int整数常量 - 它不符合NSCodingNSCopyingNSObjectProtocol。它是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来明确桥梁。

相关问题