swift 4 : Non-nominal type 'T' does not support explicit initialization

标签 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
    }
}

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

Non-nominal type 'T' does not support explicit initialization

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

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

最佳答案

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

关于 swift 4 : Non-nominal type 'T' does not support explicit initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46331351/

相关文章:

Swift - 无法更改 UILabel 中的字体样式

ios - 禁用 iMessage 应用调整大小

ios - 隐藏 View 并应用隐藏效果 - Swift

swift - 我可以在 CLCircularRegion 中设置值吗?

swift - swift 4 中的访问控制

swift - 使用 Swift 4 Codable PropertyListDecoder() 解码 PropertyList

swift - 如何在没有 "Optional"的情况下从 plist 打印字符串?

ios - 以编程方式创建的 View Controller 在显示或推送时有黑色空间

ios - 时间格式(swift 4 中的 hh :mm a) not working for iOS 11. 1.1

ios - 将视频上传到 iPhone 画廊中的特定相册