I'd like to create a matrix where the element in the cell conforms to a protocol.
Here is kind of how I envision it being implemented, but I'm getting stuck in the syntax.
extension Array where Element == Array<T>, where T: MyProtocol {
}
I'd like to create a matrix where the element in the cell conforms to a protocol.
Here is kind of how I envision it being implemented, but I'm getting stuck in the syntax.
extension Array where Element == Array<T>, where T: MyProtocol {
}
You can constrain your Collection's Element to Collection and constrain its Element.Element to your protocol:
protocol MyProtocol { }
extension Collection where Element: Collection, Element.Element: MyProtocol {
}
RandomAccessCollection instead. If you need access to methods like insert, remove, append, etc... you will need to constrain it to RangeReplaceableCollection.The generalized form of your question is, "How can I extend a generic type which has a placeholder that is also a generic type?". (The protocol part is not actually a part of your problem.)
The answer, as I showed in the other question I linked you to, is that you can't do it at the extension level. You have to do it at the method/subscript/initializer level.
It doesn't matter if the placeholder is replaced by the extended type, or not. Regardless, there's never a way to refer to a placeholder of a placeholder, in an extension declaration.
struct GenericType<PlaceHolder> { }
extension Array {
func ƒ<🤷>() where Element == GenericType<🤷> { }
subscript<🪆>(_: 🪆.Type = 🪆.self) -> Void
where Element == Array<🪆> {
get { }
}
}
extension GenericType {
init?<🧃>() where PlaceHolder == [🧃] {
nil
}
}
If you need a property, then you'll need to use at least one protocol, as Leo shows in his answer.