I am trying to create a protocol R
with an array of objects n
which can be, in principle, different classes (N1
, N2
) but all subjects of the same protocol N
. Classes that submit to the protocol R
(M1
, M2
) can decide whether their property array n
will hold only specific kind of R
or any.
This compiles just fine:
protocol N { }
class N1: N { }
class N2: N { }
protocol R {
associatedtype NType
var n: [NType] { get set }
}
class M1: R {
var n: [N] = [N1(), N2()]
}
class M2: R {
var n: [N1] = [N1(), N1()]
}
But I don't understand how to add a constraint to the associatedtype Ntype
that it must conform to N
. Something in the lines of
protocol N { }
class N1: N { }
class N2: N { }
protocol R {
associatedtype NType: N
var n: [NType] { get set }
}
class M1: R {
var n: [N] = [N1(), N2()]
}
class M2: R {
var n: [N1] = [N1(), N1()]
}
This doesn't compile saying that Type 'M1' does not conform to protocol 'R'
.