I want to initialize a enum from a variable of type String?
, like:
guard let id = request.queryParameters["id"] else {
return
}
guard let id2 = MyIdentifier(rawValue: id) else {
return
}
In this case, request.queryParameters["id"]
returns String?
. Then after I ensure that it is String
in id
, I convert it into an enum instance id2
.
However, the code is dirty and I want to write it in one-line if at all possible.
However, I don't like to make it unwrapped via forced optional unwrapping, because if it can not be transformed to String, the app would end up with an error, since rawValue:
only takes String
. I meant something like the following, which I don't like:
guard let id = MyIdentifier(rawValue: request.queryParameters["id"]!) else {
return
}
So is it still possible to define the guard let
in one-line, maybe using where
and/or case
in guard
?
Aucun commentaire:
Enregistrer un commentaire