[swift-evolution] Guard Implicit Fallback
Alexey Demedetskiy
dalog at me.com
Fri Feb 12 01:19:58 CST 2016
Hey all
Can we align `guard` statement with `as` and `try` statements?
I mean enabling `guard?` and `guard!` versions.
guard! behavior is a pretty straightforward - raise an exception if condition is false.
In this case it will look like precondition(), but with conditional bindings.
guard? is a tricky one. What actually want to say - return default value.
in Void returning functions it is simple. It can be obvious in an Optional returning functions.
But this use cases are not general enough.
In other words, to give guard? statements enough semantics, we need to provide default return value
to function signature.
So, given small setup:
typealias UserID = Int
struct User { let id: UserID }
let users = [User(id: 1), User(id: 2)]
We can write findUser(byID:) function this way:
func findUser(byId id: UserID?) -> User? {
guard let id = id else { return nil }
for user in users {
if user.id == id { return user }
}
return nil
}
And with guard? and function default return values this way:
func findUser(byId id: UserID?) -> User? = nil {
guard? let id = id
for user in users {
if user.id == id { return user }
}
}
Function default return values is an off topic here and can be moved to separate thread if anyone is interested.
Best regards,
Alexey Demedetskiy
> Hey everyone,
>
> I feel that `guard` could be a little more Swifty and would like to start a conversation concerning it.
>
> For example, I often have a function whose job depends on an optional having a value, and so I guard-let at the start and return if the guard fails. Or if the function returns an optional type, I'll simply return nil if guard fails.
>
> Can we improve on the general fallback case? Could we simply say:
>
> func noReturn() {
> guard let aValue = someOptional
> ....
> }
>
> and have that imply "else { returnvoid or nil}"
>
> What are your thoughts?
>
> Tighe
>
>
>
>
More information about the swift-evolution
mailing list