簡體   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