我在某些地方同时拥有 MyType
的 Set
和 Array
。
在这些地方,我需要过滤我的 Sequences
,你会注意到 filter
block 对于 Sequence
是相同的> 类型。
有什么方法可以实现通用的 Sequence
扩展,其中 filterFor
方法将返回正确的类型(Set
或 Array
),取决于接收器?
extension Set where Element: MyType {
func filterFor(valueToMatch:String) -> Set<MyType> {
return self.filter{
$0.myProperty.caseInsensitiveCompare(valueToMatch) == .orderedSame
}
}
}
extension Array where Element: MyType {
func filterFor(valueToMatch:String) -> [MyType] {
return self.filter{
$0.myProperty.caseInsensitiveCompare(valueToMatch) == .orderedSame
}
}
}
最佳答案
不幸的是,没有。 Set
有两个重载 filter(_:)
,具有这些类型:
-
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
-
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> Set<Self.Element>
首先是满足符合 Sequence
要求的实现。 .后者只是一个方法 Set
实现,不依赖于任何协议(protocol)。
没有通用的方法来引用 Filter
的变体返回除 Array<Self.Element>
之外的任何内容.有一个 Swift Evolution 提案来解决这个问题(SE-0174 - Change filter to return an associated type)。它已被接受,但尚未实现。
关于swift - 如何制作通用的序列过滤器包装器?过滤器包含 Set 和 Array 类型的相同 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53055664/