Agreed.
Typical instance creation on the fly would be one of them:
let label: UILabel = {
let label: UILabel = .init()
label.text = "Hello world"
label.font = .systemFont(ofSize: 12.0)
return label
}()
let label: UILabel = {
$0.text = "Hello world"
$0.font = .systemFont(ofSize: 12.0)
return $0
}(UILabel())
lazy var label: UILabel = makeLabel()
private func makeLabel() -> UILabel {
let label: UILabel = .init()
label.text = "Hello world"
label.font = .systemFont(ofSize: 12.0)
return label
}
And everytime I write one of them, I feel it's noisy. It's good if we could write simpler.
To be honest, I always wanted to write them much more simpler. The last one is acceptable though.
Yet, I'm not sure if proposed
build(_:_:)
would fit into Swift standard (although I understand this is just showing one possible use case).
I mean, this kind of global function feels a bit... hacky.
Also, I agree it's nice if this kind of expression is accepted at compiler level.
Galaxy.filter(.name == "Milky Way")
Despite this is accepted by compiler:
Galaxies.filter(\.isEmpty)
This is not:
Galaxies.filter(!isEmpty)
// nor
Galaxies.filter(!\.isEmpty)
which feels awkward. I understand the former is kind of just by-product and if you understand why or how it works, there is no wonder though.
(There's user-end workaround though):
prefix func !<T>(keyPath: KeyPath<T, Bool>) -> (T) -> Bool {
return { !$0[keyPath: keyPath] }
}
enables:
Galaxies.filter(!\.isEmpty)
I think one point is if this kind of expression should be implemented at compiler level or not.
...
However, if you need to use leading dot, what would you think prefix operators would work with @scope
?