ekazaev
(Eugene Kazaev)
1
Is there a way to write an extension referencing an instance with an associated type. I have the feeling that it is something that is supported one way or another.
Something like:
struct S<A> {
let s: A
init(s: A) {
self.s = s
}
}
extension Array where Element == S<T> {
func getAllS() -> [T] {
return map({ $0.s })
}
}
Val
(Valentin)
2
You can do this if T is a concrete type. If not you’re probably looking for parameterized extensions.
1 Like
ekazaev
(Eugene Kazaev)
3
@Val Yeah. It seems it is nit possible in current iteration. Thanks for help.
xwu
(Xiaodi Wu)
4
Define a protocol SProtocol, to which only S conforms:
protocol SProtocol {
associatedtype A
var s: A { get }
}
extension S: SProtocol { }
extension Array where Element: SProtocol {
func getAllS() -> [Element.A] {
return map { $0.s }
}
}
sveinhal
(Svein Halvor Halvorsen)
5
You can also write a general extension, and constrain the function by its parameters, including new generic arguments:
extension Array { // ← non-constrained extension
func getAllS<T>() -> [T] where Element == S<T> { // ← constrained function
map(\.s)
}
}
6 Likes