I don't love the current if let syntax, but this feels like it is fixing a very specific special case, where I'd rather see a more general addition to the language which would let us fix this ourselves
for example; If a function was allowed to access it's caller, then we could write
func ifPresent(_ block: (Any)->Void) {
if let nonNil = #caller {
block(nonNil)
}
}
which could be used as
foo?.ifPresent() {
$0.rect = .zero
}
for bonus points, we could have a way of defining default variable names when calling functions. Throw in access to the caller's string name, and you have
func ifPresent(_ block: (Any)->Void) {
if let nonNil = #caller {
block(nonNil @VariableDefaultName(#caller_string_name))
}
}
which could be used as
foo?.ifPresent() {
foo.rect = .zero
}
or
foo?.ifPresent() {
preferredName in
preferredName.rect = .zero
}
there are a bunch of other places where @VariableDefaultName would be great.
for example
networkRequest.run {
/// @VariableDefaultName has already implicitly written
/// request, data, error in
if error.isNil {
data.process()
}
}
note: we wouldn't need access to #caller if there was a way to write
extension Any {
func someFunc() {
//I can now access self, rather than needing #caller
}
}
but I don't think that is currently possible.