繁体   English   中英

如何在 Swift 中对 Collection 泛型进行约束扩展?

[英]How to make a constrained extension of Collection generic in Swift?

语境

我有一个符合协议Entity的类Profile 我还向所有 Element 是ProfileSwift Collections添加了一个搜索方法。

但是,我想让这个泛型不仅支持Profile ,而且支持符合Entity的每个对象。


代码

protocol Entity {
    var name: String { get }
}

class Profile: Entity { ... }

extension Collection where Element == Profile {
    func searched(with search: String) -> [Profile] {
        guard !(search.isEmpty) else { return self }
        return self.filter { ($0.name.lowercased().contains(search.lowercased())) }
    }
}

如何使搜索方法通用以支持符合Entity的所有对象?

首先,您应该将扩展名更改为以下代码

extension Collection where Iterator.Element: Entity

接下来,将方法的返回类型更改为

func searched(with search: String) -> [Iterator.Element]

最后,扩展可以是这样的:

extension Collection where Iterator.Element: Entity {
        func searched(with search: String) -> [Iterator.Element] {
            guard !(search.isEmpty) else { return [Iterator.Element]() }
            return self.filter { ($0.name.lowercased().contains(search.lowercased())) }
        }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM