One common solution is generic configuration function which I call with:
public func with<Value>(
_ value: Value,
do body: (_ value: inout Value) throws -> ()
) rethrows -> Value {
var value = value
try body(&value)
return value
}
We'd apply with to your example as follows:
let label = with (UILabel()) {
$0.text = "Hello World"
$0.textColor = .label
}
And here's an example that uses with in-line, copied from one of my projects:
Sometimes you will see a function like this defined as a member of a type instead of as a top-level function. For example, swift-protobuf defines it as a static member of the Message protocol, like this:
On the other hand, if you don't like the with function idea, you can make your keypath function work using a protocol. You can find the trick used in (for example) Publishers+KeyValueObserving.swift, which implements the Combine publisher(for:options:) method on NSObject.
The trick is to define a protocol, conform UIView (or even NSObject) to the protocol, and then extend the protocol where Self: UIView (or Self: NSObject). Thus: