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

前端 未结 4 1001
不知归路
不知归路 2020-12-05 18:41

I\'m modeling a owner/ownee scheme on Swift:

class Owner {
     // ...
}

protocol Ownee {
    var owner: Owner { get }
}
         


        
4条回答
  •  感情败类
    2020-12-05 19:18

    If you are coming to this thread just looking for a way to have subclasses inherit a method referring to its own type (type of Self) one workaround would be to parameterize the parent class on the child's type. e.g.

    class Foo {
        func configure(_ block: @escaping (T)->Void) { }
    }
    
    class Bar: Foo { }
    
    Bar().configure { $0... }
    

    BUT... it also seems that you can add a method in a protocol extension that would not be considered to conform in the protocol itself. I don't fully understand why this works:

    protocol Configurable {
        // Cannot include the method in the protocol definition
        //func configure(_ block: @escaping (Self)->Void)
    }
    
    public extension Configurable {
        func configure(_ block: @escaping (Self)->Void) { }
    }
    
    class Foo: Configurable { }
    
    class Bar: Foo { }
    
    Bar().configure { $0... }
    

    If you uncomment the method in the protocol definition itself you'll get the Protocol 'Configurable' requirement 'configure' cannot be satisfied by a non-final class ('Foo') because it uses 'Self' in a non-parameter, non-result type position compile error.

提交回复
热议问题