【问题标题】:Swift 4: Non-nominal type 'T' does not support explicit initializationSwift 4:非标称类型“T”不支持显式初始化
【发布时间】:2017-09-20 20:35:56
【问题描述】:

我编写了一个扩展程序,可以在 Collection 中搜索特定类型的对象。

extension Collection {
    /// Finds and returns the first element matching the specified type or nil.
    func findType<T>(_ type: T.Type) -> Iterator.Element? {
        if let index = (index { (element: Iterator.Element) in
            String(describing: type(of: element)) == String(describing: type) }) {
            return self[index]
        }
        return nil
    }
}

现在在 Xcode 9 / Swift 4 中,sn-p type(of: element)) 带有错误下划线

非标称类型 'T' 不支持显式初始化

这个错误很奇怪,因为我没有初始化一个对象。

这个答案https://stackoverflow.com/a/46114847/2854041 表明这可能是一个类型问题 - Swift 4 中的 String(describing:) 初始化程序是否发生了变化?

【问题讨论】:

  • 为什么String(describing: type(of: element)) == String(describing: type)可以直接比较类型变量,还有is可以检查类型呢?

标签: swift swift4


【解决方案1】:

您不应该使用String(describing:) 来比较值,尤其不应该使用它来比较类型。 Swift 为这两种方法都内置了方法。要检查变量是否属于某种类型,可以使用is 关键字。

此外,您还可以利用内置的first(where:) 方法并检查闭包内的类型。

extension Collection {
    /// Finds and returns the first element matching the specified type or nil.
    func findType<T>(_ type: T.Type) -> Iterator.Element? {
        return self.first(where: {element in element is T})
    }
}

测试数据:

let array: [Any] = [5,"a",5.5]
print(array.findType(Int.self) ?? "Int not found")
print(array.findType(Double.self) ?? "Double not found")
print(array.findType(Float.self) ?? "Float not found")
print(array.findType(String.self) ?? "String not found")
print(array.findType(Bool.self) ?? "Bool not found")

输出:

5
5.5
Float not found
a
Bool not found

【讨论】:

    【解决方案2】:

    这是我得到的错误

    它与type(of: 和参数type 混淆了。

    更改T.Type 参数名称后。它的工作原理:

    extension Collection {
        /// Finds and returns the first element matching the specified type or nil.
        func findType<T>(_ typeT: T.Type) -> Iterator.Element? {
            if let index = (index { (element: Iterator.Element) in
            String(describing: type(of: element)) == String(describing: typeT) }) {
                return self[index]
            }
            return nil
        }
    }
    

    【讨论】:

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