Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol Extension Initializer

I would like to know what the protocol equivalent is for an initializer in a simple class that only contains initializing functionality and is only intended to be extended in a concrete class.

So probably the easiest is to show the code - I'm looking for the protocol extension equivalent of the following:

import UIKit

class Thing {
    var color:UIColor
    init(color:UIColor) {
        self.color = color
    }
}
class NamedThing:Thing {
    var name:String
    init(name:String,color:UIColor) {
        self.name = name
        super.init(color:color)
    }
}
var namedThing = NamedThing(name: "thing", color: UIColor.blueColor())

I was expecting the code to look something like:

protocol Thing {
    var color:UIColor {get set}
}
extension Thing {
    init(color:UIColor) {
        self.color = color
    }
}
class NamedThing:Thing {
    var name:String
    var color:UIColor
    init(name:String,color:UIColor) {
        self.name = name
        self.init(color:color)
    }
}

I've seen solutions suggested in other StackOverflow questions(eg. How to define initializers in a protocol extension?) but I'm not sure they work nor specifically address this problem of additional parameters in the class initializer.

like image 212
Craig Grummitt Avatar asked Jan 14 '16 23:01

Craig Grummitt


2 Answers

protocol Thing {
    var color: UIColor {get set}
}

Awesome, no problems.

extension Thing {
    init(color: UIColor) {
        self.color = color
    }
}

No. That's never going to work. This breaks way too many rules. The first and most important is that this doesn't necessarily set all the properties. Consider your NamedThing. What is name in this case? What happens if the color setter fetches other properties that haven't been set yet? The compiler can't see every possible implementation of this yet, so it has no idea if color is just an ivar or something wildly more complicated. No, this isn't going to work.

The real problem is "an abstract class that can be extended in a concrete class." Forget classes. Forget inheritance. Swift is all about composition and protocols, not inheritance.

So let's think about the example you describe in the comments (though in Cocoa, there are no "abstract classes," either). Let's assume that setting color is in fact a lot of code that you don't want to duplicate. That's no problem. You just need a function.

import UIKit

protocol Thing {
    var color: UIColor {get set}
}

private extension Thing {
    static func colorForColor(color: UIColor) -> UIColor {
        // We don't really use the color directly. We have some complicated code that we don't want to repeat
        return color
    }
}

final class NamedThing: Thing {
    var name: String
    var color: UIColor

    init(name: String, color: UIColor) {
        self.name = name
        self.color = NamedThing.colorForColor(color)
    }
}

Since the point of your extension is to handle partial initialization, just let it calculate the part you need. Don't try to make it an initializer in an extension, since then it would have to be responsible for initializing everything, and that is very hard to do correctly when you mix it with inheritance.

like image 110
Rob Napier Avatar answered Sep 28 '22 06:09

Rob Napier


You have to provide a valid chain of init for creating an instance of a class and that limits your options for initializers in protocols.

Since your protocol can't be certain to cover all members of the class that uses it, any initializer you declare in your protocol will need to delegate initialization of the "unknown" members of the class to another initializer provided by the class itself.

I adjusted your example to illustrate this using a basic init() as the delegation initializer for the protocol.

As you can see, this requires that your class implement initial values for all members when init() is called. In this case I did that by providing default values in each member's declaration. And, since there isn't always an actual initial value for some members, I changed them to auto-unwrap optionals.

And to make thinks more interesting, your class cannot delegate initialization to a protocol supplied initializer unless it does so through a convenience initializer.

I wonder if all these restrictions are worth the trouble. I suspect you're trying to use a protocol because you need a bunch of common variables to be initialized consistently between classes that implement the protocol. Perhaps using a delegate class would provide a less convoluted solution than protocols (just a thought).

protocol Thing:AnyObject
{
    var color:UIColor! { get set }
    init()
}

extension Thing 
{    
    init(color:UIColor)
    {  
       self.init()
       self.color = color
    }
}

class NamedThing:Thing 
{
    var name:String!   = nil
    var color:UIColor! = nil

    required init() {}

    convenience init(name:String,color:UIColor) 
    {
        self.init(color:color)
        self.name = name
    }
}
like image 23
Alain T. Avatar answered Sep 28 '22 07:09

Alain T.