First, for anyone who doesn't know, guard self = self else {}
is now (finally) implemented to be valid.
I think this is sufficient for circumstances where you still want the function to run when self == nil
, but in my experience that's mostly not the case when I use [weak self]
.
Been thinking about this some and got some ideas from reading the discussion for Optional iteration. I don't like autoweak
and partially like [guard self]
, but I don't think it's necessary to add/adapt keywords when we already have syntax around optionals.
#1
let myClosure = { [weak self]? in
//self is already unwrapped
}
This would probably the simplest syntactic change and incredibly easy to add for end users, while also remaining syntactically familiar.
#2
Another option would be to put it on the right side of in
:
let myClosure = { in [weak self]?
//self is already unwrapped
}
//or since it's on the right side, in could no longer be required
let myClosure = { [weak self]? //self is already unwrapped }
This semantically puts it on the wrong side of the expression, but it would make more sense in cases where we also add a default return value:
let myClosure = { in [weak self]? else *defaultValue* // Or "[weak self] ?? *defaultValue*" ?
//self is already unwrapped
}
#3
If in?
was added as syntax, it could be a good candidate here:
let myClosure = { [weak self] in?
//self is already unwrapped
}
// with default return value
let myClosure = { [weak self] in? else *defaultValue*
//self is already unwrapped
}
To make it simple, these could compile to:
let myClosure = { [weak self] in
guard let self = self else {
return *defaultValueIfNecessary*
}
}