Kokodoko
Kokodoko

Reputation: 28158

How to override a property in Swift?

I have this Class and a subclass, from the Swift tutorial. Sadly the tutorial doesn't mention how to override a property. My first test failed miserably:

// generic shape
class Shape {
    var numberOfSides = 0
    var name: String

    init(name: String) {
        self.name = name
    }

    func simpleDescription() -> String {
        return self.name + " with \(numberOfSides) sides."
    }
}

// creating a subclass and reset the property
class Triangle: Shape {
    // this doesnt work
    override var numberOfSides = 3

    // this also doesnt work
    var numberOfSides = 3

    // and this doesnt work either
    numberOfSides = 3

    // this works
    override func simpleDescription() -> String {
        return "Triangle name: " + self.name + " number of sides: \(numberOfSides)"
    }
}

var blurgh = Triangle(name: "supertriangle")
println(blurgh.simpleDescription())

So what is the correct way to set a property on a subclass?

Upvotes: 3

Views: 1985

Answers (3)

anatoliy_v
anatoliy_v

Reputation: 1800

I'd like to extend Greg's answer. Along with get and set there are willSet and didSet options. Copy next code to playground and play with it to see how you can use it

import UIKit

class TestClass {
    var testValue: String = ""
    var anotherProperty: String = ""
}

class AnotherTestClass: TestClass {
    override var testValue: String {
        didSet {
            if countElements(super.testValue) > 2 {
                super.testValue = "222"
            }
        }
        willSet {
            if countElements(newValue) > 2 {
                super.anotherProperty = "33"
            }
        }
    }
}

var c: AnotherTestClass = AnotherTestClass()
c.testValue = "123"

Upvotes: 2

Greg
Greg

Reputation: 25459

In your example you don't want to override the property you just want to change it value. The best way to do that is init method:

init(name: String) {
    super.init(name: name)
    numberOfSides = 3
}

To override property you should make some change to it getter or setter method, for example:

override var numberOfSides  {
    get {
        return super.numberOfSides
    }
    set {
        super.numberOfSides = newValue + 10
    }
}

Upvotes: 4

zisoft
zisoft

Reputation: 23078

How about the init method?

...

func init() {
    super.init()

    self.numberOfSides = 3
}

Upvotes: 2

Related Questions