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

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

我尝试重新分配一个引用 NSLayoutConstraint。

class ViewController: UIViewController {
    @IBOutlet weak var myConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
        exchangeConstraint(&myConstraint)
    }
}

extension UIViewController {
    func exchangeConstraint(_ constraint: inout NSLayoutConstraint) {
        let spacing = constraint.constant
        view.removeConstraint(constraint)
        constraint = view.topAnchor.constraint(equalTo: anotherView.topAnchor, constant: spacing)
        view.addConstraint(constraint)
    }
}

但是这里它给了我错误:

exchangeConstraint(&myConstraint)
-------------------^
Cannot pass immutable value of type 'NSLayoutConstraint' as inout argument

我不明白的是为什么它说不可变值,而约束被声明为变量,而不是常量。

我通过简单地将 constraint 参数声明为显式展开的 NSLayoutConstraint.

来解决它
func exchangeConstraint(_ constraint: inout NSLayoutConstraint!) {
    ...
}

更新

这是我使用它的一个项目:https://github.com/truffls/compatible-layout-anchors-ios