swift 中以下闭包语法之间的区别是什么

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

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)
   }
})

// 或

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

   }
   println(result)
})

我是 Swift 编程语言的新手,最近尝试使用 swift 语言,但对闭包的语法和使用感到完全困惑。任何人都可以帮助解释这两种语法的区别,为什么它在第二种语法中工作正常但在第一种语法中工作不正常。

提前致谢。编码愉快。

我认为你正在使用游乐场,你可以select View -> Assistant Editor -> Show Assistant Editor 显示真实的控制台日志

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

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

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

输出

false

false

false

另外,你可以这样调用你的函数

    isTextValid("hi"){
        (result) -> () in
        println(result)
    }
    isTextValid("hi"){
        println([=11=])
    }