如何在swift中声明带参数的块?

Bra*_*Foo 12 ios objective-c-blocks swift

很难搞清楚如何使用swift正确声明/使用块.什么是以下代码的快速等价物?

谢谢.

^(PFUser *user, NSError *error) {
if (!user) {
    NSLog(@"Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew) {
    NSLog(@"User signed up and logged in through Facebook!");
} else {
    NSLog(@"User logged in through Facebook!");
}
Run Code Online (Sandbox Code Playgroud)

Gab*_*lla 14

Objective-C块的等价物是快速闭包,因此它将如下所示

{ (user: PFUser, error: NSError) in
  if (!user) {
    println("Uh oh. The user cancelled the Facebook login.");
  } else if (user.isNew) {
    println("User signed up and logged in through Facebook!");
  } else {
    println("User logged in through Facebook!");
  }
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*scu 7

你有很多方法可以在Swift中传递一个等效于函数的块.

我发现了三个.

为了理解这一点,我建议你在游乐场测试这段小代码.

func test(function:String -> String) -> String
{
    return function("test")
}

func funcStyle(s:String) -> String
{
    return "FUNC__" + s + "__FUNC"
}
let resultFunc = test(funcStyle)

let blockStyle:(String) -> String = {s in return "BLOCK__" + s + "__BLOCK"}
let resultBlock = test(blockStyle)

let resultAnon = test({(s:String) -> String in return "ANON_" + s + "__ANON" })


println(resultFunc)
println(resultBlock)
println(resultAnon)
Run Code Online (Sandbox Code Playgroud)

更新:匿名函数有2个特例.

首先是可以推断出函数签名,因此您不必重写它.

let resultShortAnon = test({return "ANON_" + $0 + "__ANON" })
Run Code Online (Sandbox Code Playgroud)

第二种特殊情况仅在块是最后一个参数时起作用,它称为尾随闭包

这是一个例子(与推断签名合并以显示Swift电源)

let resultTrailingClosure = test { return "TRAILCLOS_" + $0 + "__TRAILCLOS" }
Run Code Online (Sandbox Code Playgroud)

最后:

使用所有这些功能,我要做的是混合尾随闭包和类型推断(为了便于阅读命名)

PFFacebookUtils.logInWithPermissions(permissions) {
    user, error in
    if (!user) {
        println("Uh oh. The user cancelled the Facebook login.")
    } else if (user.isNew) {
        println("User signed up and logged in through Facebook!")
    } else {
        println("User logged in through Facebook!")
    }
}
Run Code Online (Sandbox Code Playgroud)

IMO它比ObjC更漂亮