Niv
Niv

Reputation: 547

Protocol with computed properties

Is there a specific reason that swift limits us from providing computed properties inside a protocol declaration? As we only have the opportunity to set those computed properties as extension to the protocol.

Words -> code:

Why this doesn't work- (what's the logic behind that)

protocol GridableGraph {
    
    var yTick: Float { get }
    var yTicksCount: Int { get }
    
    var xTick: Float{ get }
    var xTicksCount: Int { get }

    var maxYValue: Float { return Float(yTicksCount - 1) * yTick }
    var maxXValue: Float { return Float(xTicksCount - 1) * xTick }
}

While this does

protocol GridableGraph {
    
    var yTick: Float { get }
    var yTicksCount: Int { get }
    
    var xTick: Float{ get }
    var xTicksCount: Int { get }
}

extension GridableGraph{
    var maxYValue: Float { return Float(yTicksCount - 1) * yTick }
    var maxXValue: Float { return Float(xTicksCount - 1) * xTick }
}

Upvotes: 8

Views: 6355

Answers (1)

vrwim
vrwim

Reputation: 14380

A protocol is designed to provide an interface (a set of methods and properties), but leaves the implementation to the implementing classes.

When you have an extension to a protocol, the decision was made to have these require an implementation, to not mess up code that is inside a library or framework.

Let's say you want to extend the UITableViewDataSource protocol with a method you like. If Swift didn't require an implementation, what happens to all the UIViewControllers in UIKit that use this protocol? Technically you can call the method, but you'd then get an error because the method doesn't exist.

Swift has solved this problem by requiring an implementation when you extend a protocol. That way you can either not implement it (using the default implementation) or implement it (using the implementation in your class). This is because Apple wanted Swift to be as safe as possible.

Edit: You didn't ask why the extension requires a default implementation, you ask why you can not just place the default implementation in your protocol, but rather need to place this in an extension. I guess it is because Swift likes to keep things consistent, and because they are already allowing default implementations in protocol extensions, they might as well require the default implementations to be there.

Remember, there is nothing wrong with using multiple extensions in the same file, it's even suggested as the preferred way to split code for better overview in the Ray Wenderlich Swift Style Guide.

Upvotes: 3

Related Questions