rayascott
(Ray Scott)
1
I have this generic type:
struct ObjectFailure<T: Object> : Hashable {
let object: T
let error: Error
}
And I want to create a convenience method on Set whenever it contains an ObjectFailure<T> but is that actually possible with Swift? I've tried many things but can't get it to work. The extension doesn't know what T is obviously...
extension Set where Element == ObjectFailure<T> {
func contains(object: Object) -> Bool {
for element: Element in self {
if element.object === object {
return true
}
}
return false
}
}
cukr
2
The trick is to make contains(object:) generic
extension Set {
func contains<U>(object: U) -> Bool where Element == ObjectFailure<U> {
for element: Element in self {
if element.object == object {
return true
}
}
return false
}
}
2 Likes
Karl
(👑🦆)
3
No, you would need generic extensions for that. Hopefully we'll have them soon-ish, although possibly not in 5.1.
See this discussion for more info: Parameterized Extensions
EDIT: Or, yes, sink the generic constraint down to the individual additions, as @cukr suggests. Although this won't work for computed properties, which cannot be made generic.
2 Likes
rayascott
(Ray Scott)
4
Thank you both (@Karl) very very much! Super happy with that. :-)
2 Likes