Search code examples
iosswiftswift3immutabilityinout

Cannot pass immutable value of type 'NSObject' as inout argument


This should work, but I've got no clue why it doesn't. The code is self-explanatory.

class Themer {

   class func applyTheme(_ object: inout NSObject) {
      //do theming
   }
}

And I apply theme to the button like so:

class ViewController: UIViewController {

    @IBOutlet weak var button: UIButton!
    override func viewDidLoad() {

        super.viewDidLoad()
        Themer.applyTheme(&button)
    }

The button object is a variable, yet the compiler throws an error.


Solution

  • Since button is an object, this syntax

    Themer.applyTheme(&button)
    

    means that you want to change the reference to that object. But this is not what you want. You want to change the referenced object so you simply need to write

    Themer.applyTheme(button)
    

    Finally you also don't need the inout annotation

    class Themer {
        class func applyTheme(_ object: AnyObject) {
            //do theming
        }
    }
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var button: UIButton!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            Themer.applyTheme(self.button)
    
        }
    }
    

    But...

    However, what should your applyTheme method do? It receives AnyObject and then what? You could make it a little but more specific and use a UIView as param

    class Themer {
        class func applyTheme(view: UIView) {
            //do theming
        }
    }
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var button: UIButton!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            Themer.applyTheme(view: button)
        }
    }
    

    Now you have a chance to write meaningful code inside Themer.applyTheme.