ios 如何快速声明带有参数的块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24026497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare a block with arguments in swift?
提问by Brandon Foo
Having a hard time figuring out how to properly declare/use blocks with swift. What would be the swift equivalent of the following code?
很难弄清楚如何正确声明/使用 swift 块。以下代码的 swift 等价物是什么?
Thanks.
谢谢。
^(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!");
}
回答by Gabriele Petronella
The equivalent of Objective-C blocks are swift closures, so it would go as follows
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!");
}
}
回答by Francescu
You have many ways offered to pass a block equivalent to function in Swift.
您可以通过多种方式传递与 Swift 中的函数等效的块。
I found three.
我找到了三个。
To understand this I suggest you to test in playground this little piece of code.
要理解这一点,我建议您在操场上测试这段代码。
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)
Update: There are 2 special cases to the Anonymous function.
更新:匿名函数有两种特殊情况。
The first is that function signature can be inferred so you don't have to rewrite it.
第一个是可以推断函数签名,因此您不必重写它。
let resultShortAnon = test({return "ANON_" + let resultTrailingClosure = test { return "TRAILCLOS_" + 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!")
}
}
+ "__TRAILCLOS" }
+ "__ANON" })
The second special case works only if the block is the last argument, it's called trailing closure
第二个特殊情况只有当块是最后一个参数时才有效,它被称为尾随闭包
Here is an example (merged with inferred signature to show Swift power)
这是一个示例(与推断签名合并以显示 Swift 功能)
{ (user: PFUser?, error: NSError) -> {} in
if (nil == user) ...
}
Finally:
最后:
Using all this power what I'd do is mixing trailing closure and type inference (with naming for readability)
使用所有这些功能,我要做的是混合尾随闭包和类型推断(为了可读性而命名)
let afterSignInAttempt: (PFUser?, NSError) -> Void = { user, error in
if(!user){
NSLog("Uh oh.")
} else {
user.isNew ? NSLog("Signed up") : NSLog("User Logged in")
}
}
IMO it's more beautiful than in ObjC
IMO 它比 ObjC 更漂亮
回答by Ashok
回答by GoZoner
Critically, if user
can be nil
then it must bedeclared as an Optional. Thus:
至关重要的是,如果user
可以,nil
则必须将其声明为 Optional。因此:
class IDDBlockTime {
// return time elapsed in milliseconds
//
static func timeSpent(_ block: (Void) -> Void) -> TimeInterval {
let methodStart = Date()
block()
return Date().timeIntervalSince(methodStart) * 1000.0
}
}
noting that the type for user
includes ?
to indicate that user
is an optional argument(either nil
or of type PFUser
).
请注意,user
includes的类型?
表示这user
是一个可选参数(nil
或 type PFUser
)。
Other answers, that don't use an Optional, won't even compile.
其他不使用 Optional 的答案甚至不会编译。
回答by Dan Hixon
See if this works for you. It's crazy trying to learn this on day two.
看看这是否适合你。想在第二天学习这个真是太疯狂了。
let timeSpent = IDDBlockTime.timeSpent {
// lines of code you want to measure
//
self.doSomethig()
}
print("timeSpent: '\(timeSpent) ms'")
回答by Klajd Deda
// define it
// 定义它
##代码##// use it
// 用它
##代码##