Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 820
Lukas Würzburger Avatar asked Dec 06 '17 09:12

Lukas Würzburger


1 Answers

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

like image 123
Lukas Würzburger Avatar answered Nov 07 '22 12:11

Lukas Würzburger