簡體   English   中英

參數類型'Int'不符合預期類型'NSCoding&NSCopying&NSObjectProtocol'

[英]Argument type 'Int' does not conform to expected type 'NSCoding & NSCopying & NSObjectProtocol'

我是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)
]

我從答案中得到了另一種解決方案。 雖然它有效,但我仍然不清楚問題和解決方案。 我錯過了什么概念。

由於ORKTextChoice的初始化器具有value:的抽象參數類型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:完全消除Swift的隱式橋接轉換 ,現在不再是這種情況了。 您需要使用as顯示橋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM