Animate Constraint Multipliers | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/18411703-uikit-animation/lessons/6

Jessy, I was curious as to why when looping throw the constraints using the .firstItem and .firstAttribute conditions the value is as an optional before accessing the constant

constraints.first {
$0.firstItem === titleLabel && $0.firstAttribute == .centerX
}?.constant = menuIsOpen ? -100 : 0

But when looping through the constraints using the identifier the value is forced unwrapped to access the isActive property.

constraints.first {
$0.identifier == “Title Center Y”
}!.isActive = false

Wouldn’t both of these options of finding the constraint be an optional instead?

Hi Kenneth,

Because we know for sure that both of these constraints are going to be found, force-unwrapping is more informative. However, optional chaining also compiles, as you see, so I, as the programmer, wasn’t forced by the compiler to use a “!”. (If a matching constraint wasn’t found for your first example, then nothing would happen.)

I should have used a ! in both cases, for consistency, but you’re free to use whichever option you prefer.

Thanks Jessy for the confirmation. However, in this case, although I know for sure the constraints exist, I’m always reluctant to force unwrap anything unless absolutely necessary. But either way it works perfectly and I appreciate the quick response.

And it goes without saying, it’s a great course! It even helped me get a better grasp on using constraints programmatically.

1 Like