If you use the protocol method in the extension, do you need to specify the method in the protocol?

I like how Swift allows you to define a method in a protocol, and then implement this method through an extension of this protocol. However, in particular, for cases when you define a protocol and extension in the same scope and with the same access levels, do you need to determine the method in the protocol in the first place?

Consider this code:

public protocol MyProtocol {
    func addThese(a:Int, b:Int) -> Int
}

public extension MyProtocol {
    func addThese(a:Int, b:Int) -> Int{
        return a + b
    }
}

How is this different from this?

public protocol MyProtocol {
}

public extension MyProtocol {
    func addThese(a:Int, b:Int) -> Int{
        return a + b
    }
}

Note. I specifically ask that the protocol and extension are defined together in the same area with the same access levels.

If this is not so - that is. the extension has a different scope than the protocol, then it is obvious that only elements in the same area as the extension will receive an automatic implementation. It makes sense.

i.e. In module A:

public protocol MyProtocol {
    func addThese(a:Int, b:Int) -> Int
}

B

internal extension MyProtocol {
    func addThese(a:Int, b:Int) -> Int{
        return a + b
    }
}

B, MyProtocol, addThese, , MyProtocol , .

, . , ?

+4
1

, , , . , .

, UITableViewDataSource UITableViewDelegate. , , , , .

, , , .

, : https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html

, ,

, , .

+1

Source: https://habr.com/ru/post/1692002/


All Articles