I'm using Xcode 7.3 and Swift 2.3. I have difficulties using protocols with associated types that have variables. Look at the example:
protocol SomeProtocol {}
class SomeProtocolImpl: SomeProtocol {}
protocol ProtocolWithAssociatedType {
associatedtype T: SomeProtocol
var variable: T { get }
}
class TestClass: ProtocolWithAssociatedType {
var variable: SomeProtocol = SomeProtocolImpl()
}
For some reason, compiler shows errors:
How is that possible? Am I doing something wrong? Is it a bug? A known one?
What I've tried:
defined typealias for that associated type:
class TestClass: ProtocolWithAssociatedType {
typealias O = SomeProtocol
var variable: SomeProtocol = SomeProtocolImpl()
}
nope.
Used method instead:
protocol SomeProtocol {}
class SomeProtocolImpl: SomeProtocol {}
protocol ProtocolWithAssociatedType {
associatedtype T: SomeProtocol
func someMethod() -> T
}
class TestClass: ProtocolWithAssociatedType {
typealias T = SomeProtocol
func someMethod() -> SomeProtocol {
return SomeProtocolImpl()
}
}
How should I create protocol with associated type and variable and avoid this errors?