Wizard
(Benjamin)
1
Hi,
let's say I have a protocol MyProtocol and a class MyClass: MyProtocol conforming to MyProtocol.
How can I declare nested arrays of arbitrary depth of MyClass to all conform to MyProtocol? So how can I make arrays of type[MyClass], [[MyClass]], [[[MyClass]]], ... conform to MyProtocol?
An example where I see this implemented is for the Codable Protocol, as long as MyClass: Codable conforms to Codable, [MyClass].self is Codable.Type returns true, so does [[MyClass]].self is Codable.Type and so forth. This is exactly the behavior I would like to have for MyProtocol.
Making this work for [MyClass] is simple:
extension Array: MyProtocol where Element: MyClass { }
But how do I declare this for nested arrays of MyClass with arbitrary depth?
mbrandonw
(Brandon Williams)
2
Your extension is nearly correct. What you want is Element: MyProtocol:
protocol MyProtocol {}
extension Array: MyProtocol where Element: MyProtocol {}
struct Foo: MyProtocol {}
[Foo()] as MyProtocol
[[Foo()]] as MyProtocol
[[[Foo()]]] as MyProtocol
[[[[Foo()]]]] as MyProtocol
5 Likes
Wizard
(Benjamin)
3
Thank you very much. It's actually kind of embarrassing I did not think of that kind of recursion.
1 Like