2017-09-20 40 views
1

我已经写了一个扩展,它搜索某个特定类型的对象的CollectionSwift 4:非标称类型'T'不支持显式初始化

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 /斯威夫特4中,摘录type(of: element))加下划线,错误

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

的错误是奇怪因为我没有初始化一个对象。

这个答案https://stackoverflow.com/a/46114847/2854041表明也许这是一个类型问题 - 在Swift 4中String(描述:)初始化器的变化吗?

+4

你为什么会做'字符串(说明:类型(:元))==字符串(描述:型)' ,当你可以直接比较类型变量,并且检查类型也有'is'? –

回答

3

这里是我得到 enter image description here

及其与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 
    } 
} 
5

你不应该使用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