我是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)
]
Run Code Online (Sandbox Code Playgroud)
我通过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)
]
Run Code Online (Sandbox Code Playgroud)
我从答案中得到了另一种解决方案.虽然它有效,但我仍然不清楚问题和解决方案.我错过了什么概念.
由于ORKTextChoice初始化器具有抽象参数类型value:,因此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)
]
Run Code Online (Sandbox Code Playgroud)
你的原始代码在Swift 3之前可以工作,因为Swift类型能够隐式桥接到它们的Objective-C对应物.但是,根据SE-0072:完全消除Swift的隐式桥接转换,现在不再是这种情况了.您需要使用显式桥as.
| 归档时间: |
|
| 查看次数: |
2230 次 |
| 最近记录: |