Reputation: 169
I am trying to implement protocol oriented class watching tutorials from on of the popular tutorial sites. I got everything correct so far but for some reason one of the properties is not being updated while the others are updated. Here is the code :
protocol Paintable : class {
var primaryBodyColor : String{get set}
var secondaryBodyColor : [String]? {get set}
func paint(newPrimaryColor : String, newSecondaryColor : [String]?)
}
extension Paintable {
var primaryBodyColor : String {
get {
return "Black"
}
set {
}
}
}
protocol Wheeled {
var numberOfWheels : Int {get set}
}
extension Wheeled {
var numberOfWheels : Int {
get {
return 4
}
set {
}
}
}
protocol EngineSize {
var engineSizeCC : Int {get set}
}
extension EngineSize {
var engineSizeCC : Int {
return 2300
}
}
class Honda : Transport, Paintable, Wheeled, EngineSize {
var secondaryBodyColor : [String]?
var engineSizeCC : Int
//We can also override default initializer of protocol, here we are going to instantiate with our initializer
init(engineSizeCC : Int){
self.engineSizeCC = engineSizeCC
}
func paint(newPrimaryColor: String, newSecondaryColor: [String]?) {
primaryBodyColor = newPrimaryColor
secondaryBodyColor = newSecondaryColor
}
}
var civic = Honda(engineSizeCC: 400)
civic.primaryBodyColor
civic.passengerCapacity
civic.numberOfWheels
civic.engineSizeCC
civic.paint("blue", newSecondaryColor: ["Red","Purple"])
civic.primaryBodyColor -> "Black"
civic.secondaryColor -> ["Red"], ["Purple"]
The problem I am having is the primaryBodyColor stays "Black" even though I called the "paint" function to set the primary color as "Blue" and secondary color.
I am new to protocol oreinted programming so I will appreciate help on resolving this issue.
Upvotes: 2
Views: 325
Reputation: 9042
Extensions cannot store properties, which is perhaps why you don't have any code in the setter of primaryBodyColor
. The implementation of primaryBodyColor
needs to be in a struct/class, just as you've done with seondaryBodyColor
. So if just before that line within the Honda class you include the following line, your code will work as expected...
var primaryBodyColor = "black"
Upvotes: 2
Reputation: 19922
Like it's been said in the comments, your implementation of the primaryBodyColor
always return black and doesn't allow to be set.
By default, properties in Swift have a get
and set
method, there's no need to add {get set}
after each one of them.
If you want to add a default value, you can do it like this:
var primaryBodyColor = "Black"
You don't even need to declare it as String because the compiler will realize that "Black"
is a string and type it correctly.
Upvotes: 1