If an operator with multiple conditions in Swift

I have an if statement where I would like to have two conditions:

if let name = json["resource"]["fields"]["name"].stringValue && name.hasPrefix("/")

When I do this, I have a "Using an unresolved identifier name" error. What is the solution then?

if let name = json["resource"]["fields"]["name"].stringValue && "test".hasPrefix("/"){

If I do this instead, I get the error message "Optional type" $ T16 "cannot be used as a boolean, instead of"! = Nil "instead of"

This is probably a stupid question, but I have to admit that I'm lost ...

thanks for the help

+4
source share
1 answer

You are not using a regular if statement, you are using an optional binding, and you cannot combine the binding with checking the associated value. You could break it into something like this.

if let name = json["resource"]["fields"]["name"].stringValue {
    if name.hasPrefix("/") {
        // stuff
    }
}

. , Swift 1.2. , if let, :

"if let" , if ( while) , :

if let name = json["resource"]["fields"]["name"].stringValue where name.hasPrefix("/") {
    // stuff
}

, . ()

+6

All Articles