0

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.

Aswath
  • 1,236
  • 1
  • 14
  • 28

2 Answers2

2

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.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • 3
    Note that you *can* use `inout` with reference types – it allows the function to change the reference of the variable that's passed to it. Although you're right that it's probably not what OP wants. – Hamish Nov 11 '16 at 12:00
  • @Hamish You are right, I'll correct my statement. Thank you! – Luca Angeletti Nov 11 '16 at 12:01
  • I knew I was doing something wrong when I found no questions like mine though this should be common. Thanks – Aswath Nov 11 '16 at 12:53
1

inout is for the case that you want to change the reference, that is replace one object with another object. That's a very, very, very bad thing to do with an IBOutlet. That button is used in a view, connected up to lots of things, and if you change the variable, all hell will break lose.

Apart from that, listen to appzYourLife.

gnasher729
  • 51,477
  • 5
  • 75
  • 98