3

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

2 Answers 2

3

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 }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Simple loop and optional chcecking

func isSetupDone(token1: String?, token2: String?, token3: String?) -> Bool{
    let array = [token1, token2, token3]
    for case let element in array {
        if let element = element , !element.isEmpty {
            // do nothing
        } else {
            return false 
        }
    }
    return true 
}

1 Comment

Empty if branches are an anti-pattern. If you only need the else branch, negate the condition rather than creating an empty if branch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.