I am currently trying to implement some of the principles of protocol oriented programming to my data models. The problem is that I have quite a substantial amount of structs that conform to the protocol and I am finding that I have to write a lot of boilerplate code before my models can work with the protocols.
In the code below you can see that I have to provide an implementation for the "name" and "type" property everywhere. I am wondering if there is a way for me to declare these properties once and have it implemented for all the structs conforming to ColumnProtocol. I am aware that I can use extensions but these only provided computed properties (i.e. a get and set method) and I cannot use this.
protocol ColumnProtocol {
var name: String {get}
var type: ColumnType {get}
var valueRange: [Any]? {get}
}
extension ColumnProtocol {
//By default valueRange is nil
var valueRange: [Any]? {
get {
return nil
}
}
}
struct BlueprintColumnDouble: BlueprintColumnProtocol{
let type = ColumnType.double
let name: String
}
struct BlueprintColumnInt: BlueprintColumnProtocol{
let type = ColumnType.int
let name: String
}
struct BlueprintColumnBoolean: BlueprintColumnProtocol{
let type = ColumnType.boolean
let name: String
}
struct BlueprintColumnDate: BlueprintColumnProtocol{
let type = ColumnType.date
let name: String
let valueRange: [Any]?
init(name: String, valueRange: [Any]?){
if let _ = valueRange {
let check = type.checkTypeOfArray(valueRange!)
assert(check, "The value type for the range is not correct")
}
self.valueRange = valueRange
self.name = name
}
}
Thanks in advance.