Search code examples
setswift4varsetter

How to create a custom getter method in Swift?


I am trying to create a custom setter method for my property using the code below:

var myProperty: String {
    get {
        if CONDITION1 {
            return CONDITION1_STRING
        } else if CONDITION2 {
            return CONDITION2_STRING
        } else{
            return myProperty
        }
    }
    set {
        
    }
}

But this gives the warning:

Attempting to access 'myProperty' within its own getter


Solution

  • Create a backing ivar and add a custom setter:

    private var _myProperty: String 
    var myProperty: String {
        get {
            if CONDITION1 {
                return CONDITION1_STRING
            } else if CONDITION2 {
                return CONDITION2_STRING
            } else {
                return _myProperty
            }
        }
        set {
            _myProperty = newValue
        }
    }