-1

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.

Rameswar Prasad
  • 1,331
  • 17
  • 35

1 Answers1

1

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)
    }
Community
  • 1
  • 1
Leo
  • 24,596
  • 11
  • 71
  • 92
  • 3
    I would just add, that you don't need to run it in simulator to see actual console output - you can see it in playground too: View -> Assistant Editor -> Show Assistant Editor – Jakub Vano Jun 05 '15 at 07:36
  • Thanks both of you, it did show the correct result. Yes I'm using playground, is there any difference in seeing the console logs shown in assistant editor and standard editor ? I'm not sure still why the outputs differ in the two different editors. – Rameswar Prasad Jun 05 '15 at 07:53