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

And*_*ber 1 swift swift4

我写了一个扩展,搜索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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在Xcode 9/Swift 4中,该代码段type(of: element))带有错误下划线

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

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

这个答案/sf/answers/3228039321/表明它可能是一个类型问题 - 在Swift 4中String(描述:)初始化器是否发生了变化?

Dáv*_*tor 6

您不应该使用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})
    }
}
Run Code Online (Sandbox Code Playgroud)

测试数据:

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")
Run Code Online (Sandbox Code Playgroud)

输出:

5
5.5
Float not found
a
Bool not found
Run Code Online (Sandbox Code Playgroud)