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 i
Here's what I had in mind for the "delegate class".
It's a technique I use to add stored variables to a class using protocols.
class ManagedColors
{
var color:UIColor
// other related variables that need a common initialisation
// ...
init(color:UIColor)
{
self.color = color
// common initialisations for the other variables
}
}
protocol ManagedColorClass
{
var managedColors:ManagedColors { get }
}
extension ManagedColorClass
{
// makes properties of the delegate class accessible as if they belonged to the
// class that uses the protocol
var color:UIColor {
get { return managedColors.color }
set { managedColors.color = newValue }
}
}
// NamedThing objects will be able to use .color as if it had been
// declared as a variable of the class
//
// if you add more properties to ManagedColors (and the ManagedColorHost protocol)
// all your classes will inherit the properties as if you had inherited from them through a superclass
//
// This is an indirect way to achive multiple inheritance, or add additional STORED variables with
// a protocol
//
class NamedThing:ManagedColorClass
{
var name:String
var managedColors:ManagedColors
init(name:String,color:UIColor)
{
managedColors = ManagedColors(color:color)
self.name = name
}
}
let red = NamedThing(name:"red", color:UIColor.redColor())
print(" \(red.name) \(red.color)")