从Swift 2.0开始,我们似乎可以更接近于适用于预测情况的泛型类型的扩展.

尽管我们仍然无法做到这一点:

protocol Idable {
    var id : String { get }
}

extension Array where T : Idable {
    ...
}

...我们现在可以这样做:

extension Array {
    func filterWithId<T where T : Idable>(id : String) -> [T] {
    ...
    }
}

...Swift 在语法上接受了它.然而,就我个人而言,当我填写示例函数的内容时,我不知道如何让编译器满意.假设我尽可能明确地说:

extension Array {
    func filterWithId<T where T : Idable>(id : String) -> [T] {
        return self.filter { (item : T) -> Bool in
            return item.id == id
        }
    }
}

...编译器不会接受提供给筛选器的闭包,因此会抱怨

Cannot invoke 'filter' with an argument list of type '((T) -> Bool)'

如果项目被指定为可识别,则类似.有人在这里走运吗?

推荐答案

extension Array {
    func filterWithId<T where T : Idable>(id : String) -> [T] {
    ...
    }
}

定义泛型方法filterWithId(),其中泛型方法

所以您已经指定数组元素必须符合

从Swift 2/Xcode 7 beta 2开始,您可以在泛型类型上定义对模板更严格的扩展方法

extension Array where Element : Idable {

    func filterWithId(id : String) -> [Element] {
        return self.filter { (item) -> Bool in
            return item.id == id
        }
    }
}

或者,您可以定义protocol extension method:

extension SequenceType where Generator.Element : Idable {

    func filterWithId(id : String) -> [Generator.Element] {
        return self.filter { (item) -> Bool in
            return item.id == id
        }
    }
}

然后filterWithId()适用于所有类型

Swift 3年后这将是

extension Sequence where Iterator.Element : Idable {

    func filterWithId(id : String) -> [Iterator.Element] {
        return self.filter { (item) -> Bool in
            return item.id == id
        }
    }
}

Swift相关问答推荐

使用简单变量和函数的奇怪行为

通过SwiftUI中的列表 Select 从字典中检索值

如何为任务扩展的泛型静态函数获得自动类型推理

如何使 onKeyPress 与 TextField 快速配合使用?

物理主体未与 spritekit Swift 的网格图案上的纹理图像对齐

TabView 无法在屏幕上正确显示

如何在不将变量转换为字符串的情况下判断变量在 Swift 中是否为 Optional(nil)?

swift 是否遇到 Java 的 2gb 最大序列化大小问题?

用逻辑运算符保护让

当使用 CGFloat 而不是数字文字时,为什么 node 的位置会发生变化?

iOS16 Bug 键盘在表单解雇 SwiftUI 时打破布局

Swift 全局函数列表

Swift:创建用于调用 C 函数的指针数组

如何在 SwiftUI 的 fileImporter 中为 allowedContentTypes 设置 xcodeproj 类型?

如何仅将 SwiftUI 不透明度应用于父视图?

在swift 3中将文件保存在文档目录中?

否定 #available 语句

Swift 动画 WithDuration 语法是什么?

3D touch /强制touch 实现

如何使用 swift 将 Images.xcassets 中的图像加载到 UIImage 中