Check string for nil & empty

后端 未结 23 1329
感动是毒
感动是毒 2020-12-07 10:53

Is there a way to check strings for nil and \"\" in Swift? In Rails, I can use blank() to check.

I currently have this, but i

23条回答
  •  再見小時候
    2020-12-07 11:07

    Using the guard statement

    I was using Swift for a while before I learned about the guard statement. Now I am a big fan. It is used similarly to the if statement, but it allows for early return and just makes for much cleaner code in general.

    To use guard when checking to make sure that a string is neither nil nor empty, you can do the following:

    let myOptionalString: String? = nil
    
    guard let myString = myOptionalString, !myString.isEmpty else {
        print("String is nil or empty.")
        return // or break, continue, throw
    }
    
    /// myString is neither nil nor empty (if this point is reached)
    print(myString)
    

    This unwraps the optional string and checks that it isn't empty all at once. If it is nil (or empty), then you return from your function (or loop) immediately and everything after it is ignored. But if the guard statement passes, then you can safely use your unwrapped string.

    See Also

    • Statements documentation
    • The Guard Statement in Swift 2

提交回复
热议问题