How to check Multiple string is not nil and not empty in swift 5?

user7423463

I want to check multiple string in if condition if are not nil and not empty.

for now i am doing like

  func isSetupDone(token1: String?, token2: String?, token3: String?) -> Bool{

        if token1 == nil || token1!.isEmpty || token2 == nil  || token2!.isEmpty || token3 == nil || token3!.isEmpty {
            return false
        }
        else{
            return true
        }
    }

but i guess there should be better way of doing this in swift 5. Please suggest if any

Dávid Pásztor

You can add all Strings to an Array and call allSatisfy on that array.

func isSetupDone(token1: String?, token2: String?, token3: String?) -> Bool {
    let tokens = [token1, token2, token3]
    return tokens.allSatisfy { $0 != nil && $0?.isEmpty == false }
}

You can also merge the two conditions into a single one by optional chaining the optional strings, since $0?.isEmpty == false will evaluate to false in case $0 is nil.

func isSetupDone(token1: String?, token2: String?, token3: String?) -> Bool {
    [token1, token2, token3].allSatisfy {$0?.isEmpty == false }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related