【问题标题】:Protocol 'Numeric' can only be used as a generic constraint because it has Self or associated type requirements协议“数字”只能用作通用约束,因为它具有自身或关联的类型要求
【发布时间】:2020-05-20 11:40:49
【问题描述】:

我有以下由同事编写的 swift 代码。

我不知道斯威夫特。

我一直在 xcode 中运行“产品”->“存档”,以便可以发布到 App Store。

以下代码已经存在很长时间了,我没有更改它,但我现在收到错误“协议'数字'只能用作通用约束,因为它具有 Self 或关联类型要求”。

有谁知道问题出在哪里? ……你能解释一下吗?

非常感谢任何帮助。

import Foundation

func MyCallback(_ id: String, _ with: Any?) -> String{
    return "My.callback('\(id)', \(with != nil ? with is Numeric ? with! : "'\(with!)'" : "void 0"));"
}

【问题讨论】:

    标签: swift xcode


    【解决方案1】:

    IMO 乍一看,这段代码看起来很糟糕。这不是你在 Swift 中解包选项的方式。无论如何,如果withNumeric 类型或String,您可以简单地尝试将其转换为String,而不是检查它是否是Numeric

    func MyCallback(_ id: String, _ with: Any?) -> String {
        if let string = with as? String {
            return "My.callback('\(id)', '\(string)');"
        } else if let with = with {
            return "My.callback('\(id)', \(with));"
        }
        return "My.callback('\(id)', void 0);"
    }
    

    请注意,以小写字母 func myCallback 开头的方法命名是 Swift 命名约定。

    【讨论】:

      猜你喜欢
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多