简体   繁体   English

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

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

Context语境

I have a class Profile which conforms to protocol Entity .我有一个符合协议Entity的类Profile I am also adding a search method to all Swift Collections where the Element is a Profile .我还向所有 Element 是ProfileSwift Collections添加了一个搜索方法。

However, I would like to make this generic to support not only Profile but every object conforming to Entity .但是,我想让这个泛型不仅支持Profile ,而且支持符合Entity的每个对象。


Code代码

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())) }
    }
}

Question

How can I make the search method generic to support all objects conforming to Entity ?如何使搜索方法通用以支持符合Entity的所有对象?

first, you should change the extension to the below code首先,您应该将扩展名更改为以下代码

extension Collection where Iterator.Element: Entity

next, change the return type of the method to接下来,将方法的返回类型更改为

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

Finally, the extension can be like this:最后,扩展可以是这样的:

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.

相关问题 将泛型的扩展限制为 swift 中的另一个泛型 - Extension for generic constrained to another generic in swift 如何将集合的 Swift 扩展限制为泛型类型? - How to restrict a Swift extension of a collection to a generic type? Swift 扩展 - 必须在非专用泛型类型“数组”上声明约束扩展 - Swift extension - Constrained extension must be declared on the unspecialized generic type 'Array' 如何在 Swift 中进行通用扩展? - How can I make a generic extension in Swift? 具有约束类型的Swift协议扩展约束到集合,不能使用下标 - Swift Protocol Extension with AssociatedType Constrained to Collection, Can't Use Subscript 如何对 Swift 中的所有数字类型进行通用扩展? - How can I make a generic extension on all number types in Swift? 如何使用受限于泛型类型的属性和 Swift 中的协议初始化 class - How to initialize a class with a property that is constrained to a generic type and a protocol in Swift 如何使用通用约束类型属性实现Swift协议? - How do I implement a Swift protocol with a generic constrained type property? Swift:Dictionary by Dictionary的约束扩展 - Swift: Constrained extension on Dictionary by Element Swift 通用 function 受 class 通用约束 - Swift generic function constrained by class generic
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM