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

670 Views Asked by At

I try to reassign an referecend 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)
    }
}

But here it gives me the error:

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

What i don't understand is why it says immutable value, whereas the constraint is declared as a variable, not a constant.

1

There are 1 best solutions below

0
On BEST ANSWER

I solved it by simply declaring the constraint parameter as an explicitly unwraped NSLayoutConstraint.

func exchangeConstraint(_ constraint: inout NSLayoutConstraint!) {
    ...
}

UPDATE

Here is a project where I use it: https://github.com/truffls/compatible-layout-anchors-ios