barndog
barndog

Reputation: 7173

Swift Protocol using associated types and Self?

Given this protocol:

protocol SomeProtocol { 
    associatedtype MyCustomType

    static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self?
}

why does this:

extension MyClass: SomeProtocol {
    static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self? {
        return MyClass()
    }
}

not compile? The error is: cannot convert return expression of type 'MyClass" to return type "Self?. Why in the heck doesn't this work? If it doesn't, whats the point of even using Swift in the first place? If I can't build type-safe protocols and I'm forced to type-erase it all anyway, what's the point? Can someone help me out?

EDIT:

the issue was not the associated type, it was return Self?

Upvotes: 0

Views: 62

Answers (1)

ukim
ukim

Reputation: 2465

You need to make MyClass final and replace the Self returned in MyClass extension with MyClass.

protocol SomeProtocol {
    static func someCustomStaticFunction() -> Self?
}

final class MyClass {

}

extension MyClass: SomeProtocol {
    static func someCustomStaticFunction() -> MyClass? {
        return MyClass()
    }
}
  1. We can only use Self in protocol but not class extension.
  2. You need to make MyClass final. If not, let's say you have a sub class called MySubclass, it must also confirm to SomeProtocol as its parent. So MySubclass must have someCustomStaticFunction() -> MySubclass. However, MyClass already has this function implemented but with different return type. Swift does not support overload return type at the moment, as a result, we must not subclass MyClass, this is make it final.

Upvotes: 1

Related Questions