@Erica_Sadun thank you Erica. What do you think about two other versions of the function.
-
Extension on
Anyas presented above (it will work nicely with optional chaining but is similar to.dynamicTypewhich we want to avoid) -
A left assignment operator instead of the
withfunction:
precedencegroup LeftAssignmentPrecedence {
associativity: left
higherThan: BitwiseShiftPrecedence
assignment: true
}
infix operator <- : LeftAssignmentPrecedence
@discardableResult
public func <- <T>(lhs: T, rhs: (inout T) throws -> Void) rethrows -> T {
var value = lhs
try rhs(&value)
return value
}
According to this reply the operator can work with optional chaining.
Small example of it's usage (click to unfold)
topGradientView <- {
$0.prepareForAutoLayout()
$0.attach(to: pickerHost)
NSLayoutConstraint.activate(
$0.topAnchor.constraint(equalTo: pickerHost.topAnchor)
<- { $0.priority = .defaultHigh },
$0.bottomAnchor.constraint(equalTo: backgroundView.topAnchor)
<- { $0.priority = .defaultLow },
$0.leadingAnchor.constraint(equalTo: pickerHost.leadingAnchor),
$0.trailingAnchor.constraint(equalTo: pickerHost.trailingAnchor),
$0.heightAnchor.constraint(greaterThanOrEqualToConstant: 0),
$0.heightAnchor.constraint(lessThanOrEqualToConstant: 30)
)
}