swift 回调不打印

swift callback doesn't print

我试图理解 swift 中回调的主要概念 我有以下代码:

typealias ImageHandler = (String,NSError?) -> Void

 func PostOnSocialMedia(image:String?){
    println(0)

    Post({(image)->Void in
     println(1)
    })

    println(2)
}

func Post(handler:ImageHandler){
    println(3)
}

我的代码输出是 0,3,2,我的问题是为什么不打印数字 1。

它没有打印 1,因为您传入了一个从未调用过的函数。

这个:

Post({ (image)->Void in
     println(1)
})

声明一个临时函数(一个“闭包表达式”——一种声明匿名函数的快速简便的方法,在 { } 之间),它接受一个 (String,NSError?) 对的参数,并且 returns 没什么。然后将该函数传递给 Post 函数。

但是 Post 函数对它没有任何作用。对于 运行 的函数,需要调用它。如果您像这样更改 Post 函数:

func Post(handler:ImageHandler){
    println(3)

    // call the handler that was passed in...
    handler("blah",nil)
}

你会看到它打印了一个 1。

注意,PostOnSocialMedia 接收的 image 参数和临时函数中的 image 参数变量是两个不同的变量——作用域规则是指在临时函数掩码中声明的变量外部范围内的那个。但是它们非常不同(实际上,它们是不同的类型——一种是字符串,另一种是字符串和错误的二元组)。

尝试 reading this 在 Swift 中获取有关一阶函数和闭包的简短介绍。