无法将 'NSObject' 类型的不可变值作为 inout 参数传递

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

这应该行得通,但我不知道为什么行不通。代码不言自明。

class Themer {

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

然后我将主题应用到按钮,如下所示:

class ViewController: UIViewController {

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

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

按钮对象是一个变量,但编译器会抛出错误。

因为按钮是一个对象,所以这个语法

Themer.applyTheme(&button)

表示您想更改对该对象的引用。但这不是你想要的。你想改变引用的对象,所以你只需要写

Themer.applyTheme(button)

最后你也不需要 inout 注释

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)

    }
}

但是...

但是,您的 applyTheme 方法应该做什么?它收到 AnyObject 然后呢?您可以使其更具体一些,并使用 UIView 作为参数

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)
    }
}

现在您有机会在 Themer.applyTheme.

中编写有意义的代码了

inout 适用于您想要更改引用的情况,即将一个对象替换为另一个对象。这对 IBOutlet 来说是一件非常、非常、非常糟糕的事情。该按钮在视图中使用,连接到很多东西,如果您更改变量,一切都会崩溃。

除此之外,听听 appzYourLife。