What is the difference between the below syntaxes of closures in swift

100 views Asked by At

Here is my function declaration with closure

func isTextValid(input: String, completion: (result: Bool) -> ()) {
    if input == "Hello" {
        completion(result: true)
    }
    else {
        completion(result: false)
    }
}

When I am calling the function below like this it doesn't print the right result which is "false", instead it prints "(0 elements)"

isTextValid("hi", { (result) -> () in
    println(result)
})

But when I write code like below, it works perfectly fine.

isTextValid("hi", { (result) -> () in
   if result == false {
      println(result)
   }
})

// OR

isTextValid("hi", { (result) -> () in
   if result == false {

   }
   println(result)
})

I am novice at Swift programming language, and trying my hands in swift language recently, but becoming completely baffled with the syntax and use of closure. Can anyone please help in explaining what is the difference in both of these syntaxes, why it's working fine with the second syntax but not fine in the first.

Thanks in advance. Happy coding.

1

There are 1 answers

2
Leo On BEST ANSWER

I think you are using playground,you can select View -> Assistant Editor -> Show Assistant Editor to show the real console log

isTextValid("hi", { (result) -> () in
    println(result)
})

isTextValid("hi", { (result) -> () in
    if result == false {
        println(result)
    }
})

isTextValid("hi", { (result) -> () in
    if result == false {
        
    }
    println(result)
})

Output

false

false

false

Also,you can call your function like this

    isTextValid("hi"){
        (result) -> () in
        println(result)
    }
    isTextValid("hi"){
        println($0)
    }