lundi 26 septembre 2016

Can I use "guard let" if you want to pass over an optional string to "rawValue:" in enum in Swift?

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