NSLayoutConstraint(item:, attribute:, relatedBy:, toItem:, attribute:, multiplier:, constant:)
has an item
parameter typed as Any
:
public convenience init(item view1: Any, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItem view2: Any?, attribute attr2: NSLayoutAttribute, multiplier: CGFloat, constant c: CGFloat)
But from the crash you can glean that the parameter can really only accept UIView
or UILayoutGuide
:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSLayoutConstraint for Optional(UIView: 0x7fa0fbd06650; frame = (0 0; 0 0); layer = CALayer: 0x60800003bb60): Constraint items must each be an instance of UIView, or UILayoutGuide.'
The compiler can't check for the type of item
during compile time. It is defined to accept anything. But in the implementation details that are inaccessible to us, that method accepts only non-optional UIView
s or UILayoutGuide
s.
So just add a guard
statement:
let view: UIView? = UIView()
guard let view = view else { // Proceed only if unwrapped
fatalError()
}
let _ = NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: 44.0)