Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a default value for a property with defined getter and setter

Tags:

I have a very simple class

class SimpleClass {
    var simpleDescription: String {
    get {
        return self.simpleDescription
    }
    set {
        self.simpleDescription = newValue
    }
    }
}

What is the correct way to define a default value for the simpleDescription variable?

like image 967
JuJoDi Avatar asked Jun 03 '14 22:06

JuJoDi


People also ask

How do I set default value in property?

Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.

What is the default value property?

The DefaultValue property specifies text or an expression that's automatically entered in a control or field when a new record is created.


2 Answers

In Swift, getters and setters are used for computed properties - there is no storage for the property and thus, in your case, simpleDescription can't be set in a setter.

If you need a default value, use:

class SimpleClass {
  var simpleDescription: String = "default description"
}

if you want to initialize use:

class SimpleClass {
  var simpleDescription: String
  init (desc: String) {
    simpleDescription = desc
  }
}
like image 161
GoZoner Avatar answered Nov 22 '22 04:11

GoZoner


If what you want is to perform an action each time a variable is set or just to check if the value is correct you can use Property Observers
From docs:

Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.

You can use them like this:

class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("About to set totalSteps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("Added \(totalSteps - oldValue) steps")
            }
        }
    }
}

EDIT

Looks like this doesn't work when overriding inherited properties. Here is an example of what you can't do:

class StepWihtoutCounter {
    var totalSteps: Int = 0 
}

class StepCounter: StepWihtoutCounter {
    override var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("About to set totalSteps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("Added \(totalSteps - oldValue) steps")
            }
        }
    }
like image 24
Mark E Avatar answered Nov 22 '22 06:11

Mark E