Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Attempting to access 'myProperty' within its own getter vs SwiftFormat

Tags:

getter

swift

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?

like image 923
David Silva Avatar asked Sep 23 '17 13:09

David Silva


2 Answers

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
    }
}
like image 132
Sweeper Avatar answered Nov 15 '22 08:11

Sweeper


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.

like image 29
pkamb Avatar answered Nov 15 '22 08:11

pkamb