A Swift Protocol Requirement That Can Only Be Satisfied by Using a Final Class

A Swift protocol requirement that can only be satisfied by using a final class

The Error is correct. You have to make your class final, since no subclasses could conform your protocol Ownee.

Consider this subclass:

class FirstGradeStudent: Student {
// Student contains following variable:
// var owner: Owner<Student> {
// return professor
// }
}

As you can see, it would have to implement var owner: Owner<Student> because of his parent, but it should be implementing var owner: Owner<FirstGradeStudent> instead, because the protocol contains var owner: Owner<Self> { get } and in this case Self would be FirstGradeStudent.

Workaround

1: Define a superclass to Ownee, it should be used by Owner:

class Owner<T: OwneeSuper> {
// ...
}

protocol OwneeSuper {}
protocol Ownee: OwneeSuper {
associatedtype T: OwneeSuper
var owner: Owner<T> { get }
}

OwneeSuper is just a workaround to overcome this problem, otherwise we would just be using:

protocol Ownee {
associatedtype T: Ownee
var owner: Owner<T> { get }
}

2. In classes that conform to Ownee, you must turn the abstract type of the associatedtype into a concrete class by defining a typealias:

class Student: Ownee {
typealias T = Student // <<-- define the property to be Owner<Student>
let professor: Professor
var owner: Owner<T> {
return professor
}

init(professor: Professor) {
self.professor = professor
}
}

3. Subclasses can now make use of the property, which will be of your defined type:

class FirstGradeStudent: Student {
func checkOwnerType() {
if self.owner is Owner<Student> { //warning: 'is' test is always true
print("yeah!")
}
}
}

Protocol requirement cannot be satisfied by a non-final class because it uses 'Self' in a non-parameter, non-result type

The problem has to do with the indeterminate nature of what would happen if MyClass had a subclass (because generics, such as Array, are not classes and don't magically do polymorphism). Just do what the error message says, and all will be well:

protocol MyProtocol {
static func foo(verticies:[Self]) -> Int
}
final class MyClass : MyProtocol {
class func foo(verticies:[MyClass]) -> Int {
return 1
}
}

Self, protocol extension and non-final class

Here's my understanding of what you are seeing:

  1. You get the compilation error Method 'loadFromNib' in non-final class 'UIView' must return 'Self' to conform to protocol 'NibLoadable' at the point where you declare extension UIView: NibLoadable {}. Let's look at what this statement means to the compiler. It's saying "UIView (and all of its subclasses since it is a non-final class) are adopting the NibLoadable protocol. It means, for UIView, that there will be method with the signature static func loadFromNib(name: String?) -> UIView, because Self in this context is UIView."

    But what does this mean for subclasses of UIView? They inherit their conformance and might inherit the implementation of the method from UIView itself. So any subclass of UIView could have the method with the signature static func loadFromNib(name: String? = nil) -> UIView. However, the NibLoadable protocol that all subclasses also conform to says that the return type of that method must be Self. And in the case of any UIView subclass (for example, let's say "MyView"), the return type of the inherited method will be UIView and not MyView. So any subclass would then violate the contract of the protocol. I realize that your protocol extension uses Self and wouldn't create that issue, but technically, you could still also implement the method directly in a UIView extension, and it seems like the Swift compiler just won't allow it at all for that reason. A better implementation might find the Swift compiler verifying that a protocol extension exists which provides the implementation and there is no conflicting inherited implementation, but this appears to just not exist at this time. So for safety, my guess is that the compiler prevents ANY protocols that have methods with Self return types from being adopted by a non-final class. Thus the error you see.

    However, making UIView a final class makes that whole inheritance of a non-conforming method possibility and issue go away, which fixes the error.

  2. The reason why changing the return type in the protocol to UIView fixes everything is because not having 'Self' as the return type now relieves the compiler's concern about inherited versions of the method having a non-conforming return type. E.g., if UIView were to implement the method static func loadFromNib(name: String?) -> UIView, and subclasses inherited that method, the protocol contract would still hold for those subclasses, so there is no problem!

    On the other hand, the type inference works, because the subclasses of UIView are getting their method implementation from the protocol extension (since the method is not implemented directly in UIView). That implementation returns the type Self, which tells the compiler that the returned value has the same type as the type the method was called on, and the protocol is satisfied, because any subclass of UIView will have a Self type that is a subclass of the required type of UIView.

  3. Removing the where clause works only in this specific case because you changed the protocol method to return UIView, and the protocol extension defines a matching method implementation that returns Self, and then only UIView is getting that extension in your sample code. So the protocol requirement of the method returning UIView matches the implementation UIView is getting which returns Self (which happens to be UIView in this case). But, should you try to make any type other than UIView get the protocol extension method, e.g.

    class SomeClass : NibLoadable {}

    or even

    class MyView:UIView, NibLoadable {}

    the compiler wouldn't allow it, because the Self return type in the protocol extension method would not match the UIView required in the protocol. I feel like in the case of "MyView" or other UIView subclasses though, the compiler error might be a bug, since a method that returns MyView would satisfy the protocol requirement that a method return a UIView, if MyView did inherit from UIView.

To summarize some key points:

  • It doesn't look like the protocol extension has any role in the compiler error you noted. Just this will also create the error:

    protocol NibLoadable {
    static func loadFromNib(name: String?) -> Self
    }

    extension UIView: NibLoadable {}

    So it looks like the compiler doesn't allow non-final classes to adopt protocols by using default implementations of methods that have a return type of Self, period.

  • If you change the protocol method signature to return UIView instead of Self that particular compiler warning goes away because there is no longer the possibility of subclasses inheriting a superclass return type and breaking the protocol. And you can then add conformance to the protocol to UIView with your protocol extension. However, you will get a different error if you try to adopt the protocol for any type other than UIView, because the protocol return type of UIView will not match the protocol extension method's return type of Self except in the single case of UIView. This may be a bug, in my opinion, because Self for any subclass of UIView should meet the required UIView return type contract.

  • But strangely enough, if you adopt the protocol in UIView only, subclasses of UIView will inherit their conformance to the protocol (avoiding the triggering of any of the two above compiler errors) and get their generic implementations from the protocol extension as long as UIView doesn't explicitly implement the protocol method itself. So the subclasses will get the type inference of appropriate Self, and meet the protocol contract for having that method return a UIView.

I'm pretty sure there are one or more bugs mixed up in all this, but someone on the Swift team would have to confirm that to be sure.

UPDATE

Some clarification from the Swift team in this Twitter thread:

https://twitter.com/_danielhall/status/737782965116141568

As suspected, it's a compiler limitation (though apparently not considered an outright bug) that protocol matching does not consider subtypes, only exact type matches. Which is why extension UIView:NibLoadable {} will work when the protocol method defines a return type of UIView, but extension MyView:NibLoadable {} will not.

Swift protocol property of type Set Self

The way to put constraints in protocols is similar to how you specify protocol conformance (they're the same thing after all)

protocol Groupable: Hashable
{
var parent: Self? { get }
var children: Set<Self> { get }
}

How to satisfy a protocol which includes an initializer?

Ok, my bad.

To guarantee that all subclasses conform to MyProtocol new initializer has to be marked as required as well.

Furthermore Swift requires to declare all required initializers directly within the class and does not allow to declare them in extensions.

extension MyClass : MyProtocol {
required convenience init(name: String) {
self.init()
self.name = name
}
}


Related Topics



Leave a reply



Submit