I have the following protocol and a class that conforms to it:
protocol Foo{
typealias BazType
func bar(x:BazType) ->BazType
}
class Thing: Foo {
func bar(x: Int) -> Int {
return x.successor()
}
}
When I try to create an Array of foos, I get an odd error:
var foos: Array<Foo> = [Thing()]
Protocol Foo can only be used as a generic constraint because it has Self or associated type requirements.
OK, so it can only be used if it has an associated type requirement (which it does), but for some reason this is an error?? WTF?!
I'm not sure I fully understand what the compiler is trying to tell me...
Let's say, if we could put an instance of
Thinginto arrayfoos, what will happen?Because
AnotherThingconforms toFootoo, so we can put it intofoosalso.Now we grab a
foofromfoosrandomly.and I'm going to call method
bar, can you tell me that I should send a string or an integer tobar?foo.bar("foo")orfoo.bar(1)Swift can't.
So it can only be used as a generic constraint.
What scenario requires a protocol like this?
Example: