Reputation: 2340
I have a protocol with an associatedtype and I made some of my classes conform to it:
protocol MyProtocol {
associatedtype MyType
func myFunction()-> MyType
}
struct MyStruct: Codable {
var myVar: Int
}
class MyClass1: MyProtocol {
func myFunction()-> [MyStruct]? {
return [MyStruct(myVar: 1)]
}
}
class MyClass2: MyProtocol {
func myFunction()-> Int? {
return 1
}
}
Now I want to create a protocol that can only be applied to an object that is conform to MyProtocol
and its associatedtype is an array of Codable like so:
protocol MyProtocolCodable where Self: MyProtocol, MyType: [Codable] {} 🛑
However I get an error:
Type 'Self.MyType' constrained to non-protocol, non-class type '[Codable]' (aka 'Array<Decodable & Encodable>')
How can I get around this problem and apply my restriction?
Note: I get the same error when trying to restrict with any kind of Array, but works fine with other types:
protocol MyProtocolCodable where Self: MyProtocol, MyType: [Int] {} 🛑
protocol MyProtocolCodable where Self: MyProtocol, MyType: Array<Any> {} 🛑
Upvotes: 2
Views: 149
Reputation: 15
You should use '==' to make associatedType constraints, replace yours instead of:
protocol MyProtocolCodable where Self: MyProtocol, MyType == [Codable] {}
Upvotes: 0
Reputation: 54436
This is because Array
is not a protocol, it's a struct:
@frozen struct Array<Element>
You can try to conform to Sequence
instead:
protocol MyProtocolCodable where Self: MyProtocol, MyType: Sequence, MyType.Element: Codable {}
Upvotes: 4