6

I have code like this:

@IBInspectable var myProperty: String? {
    set(newValue) {
        //logic for setter
    }
    get {
        return myProperty
    }
}

The above code generates a warning:

Attempting to access 'myProperty' within its own getter. Access 'self' explicitly to silence this warning.

So I fix the code as suggested:

@IBInspectable var myProperty: String? {
    set(newValue) {
        //logic for setter
    }
    get {
        return self.myProperty
    }
}

The problem would be solved but I am using SwiftFormat during the application build phase. And SwiftFormat automatically removes the self keyword, treating it as unnecessary here.

I see two solutions:

  1. Turn off the redundantSelf rule in SwiftFormat.
  2. Modify (how?) the code to be acceptable for both the compiler and the SwiftFormat.

What would be the best choice for this?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
David Silva
  • 1,939
  • 7
  • 28
  • 60
  • 3
    Your getter recursively calls itself, so that is wrong anyway (leading to a stack overflow quickly) – with or without warning. Compare https://stackoverflow.com/q/24025340/1187415. – Martin R Sep 23 '17 at 13:45

2 Answers2

6

Your code is incorrect in the first place. Adding self will not help.

What you have created is infinite recursion. When myProperty's getter is called, you return myProperty, which calls the getter again. in the getter you return myProperty again and this calls the getter again. This will go on forever until the stack overflows.

If you just want a custom setter, you can try willSet or didSet.

var myProperty: String {
    willSet(newValue) {
        // do stuff
    }
}

// or

var myProperty: String {
    didSet(oldValue) {
        // do stuff
    }
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

I hit this same warning when attempting to write an Objective-C style property with a backing ivar:

var myProperty: String {
    guard let myProperty = _myProperty else {
        _myProperty = "some string"
        return myProperty // Attempting to access 'myProperty' within its own getter
    }
    return myProperty
}
var _myProperty: String? = nil

Expanding the error message in Xcode, however, shows that the warning has a hint on the second line:

// Attempting to access 'myProperty' within its own getter
// Access 'self' explicitly to silence this warning

Changing to return self.myProperty thus silences the warning in cases where the calls will not cause infinite recursion.

pkamb
  • 33,281
  • 23
  • 160
  • 191