ios Swift 中块的语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24038713/
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
Syntax of Block in Swift
提问by Ryan Heitner
I am trying to rewrite from Objective-C to Swift, I cannot work out the syntax or understand the docs
我正在尝试从 Objective-C 重写为 Swift,我无法计算出语法或理解文档
Here is a simplified example in Objective-C I wrote:
这是我在 Objective-C 中写的一个简化示例:
[UIView animateWithDuration:10.0 animations:^{self.navigationController.toolbar.frame = CGRectMake(0,10,0,10);}];
How do I write this in Swift?
我如何用 Swift 写这个?
This is the template autocomplete gives:
这是模板自动完成提供:
UIView.animateWithDuration(duration: NSTimeInterval, animations: (() -> Void))
采纳答案by Jiaaro
Since the expected argument types and return type to the animations argument are known the compiler can infer them without a problem. This should work (though I don't have the playground available right at the moment:
由于动画参数的预期参数类型和返回类型是已知的,编译器可以毫无问题地推断它们。这应该可以工作(尽管我目前没有可用的操场:
UIView.animateWithDuration(10.0, animations: {
self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
})
for more info about closures see the chapter in the swift docs
note about CGRect()
- the developer docsshow CGRect()
being used in swift code. Perhaps it requires an import?
请注意CGRect()
-开发人员文档显示CGRect()
正在 swift 代码中使用。也许它需要导入?
update for comments: you can also use a trailing closure like so:
评论更新:您还可以使用像这样的尾随闭包:
UIView.animateWithDuration(10.0) {
self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
}
回答by 67cherries
This is the swift closure format:
这是快速关闭格式:
{(parameter:type, parameter: type, ...) -> returntype in
//do stuff
}
This is what you should do:
这是你应该做的:
//The animation closure will take no parameters and return void (nothing).
UIView.animateWithDuration(duration: NSTimeInterval, animations: {() -> Void in
//Animate anything.
})
Here is the documentationfor closures.
这是闭包的文档。
回答by Prakash Raj
Following code can guide to write your own block.
以下代码可以指导您编写自己的块。
class func testFunc(completion: ((list : NSArray!) -> Void)?) {
//--- block code.
if completion! != nil {
completion! (list: NSArray())
}
}
and you can call it like -
你可以这样称呼它——
className.testFunc {
(list: NSArray!) -> Void in
}
回答by Honey
You can basically write it in 3 identical ways:
您基本上可以用 3 种相同的方式编写它:
write what to do right in the closure/code block:
在闭包/代码块中写下正确的做法:
UIView.animateWithDuration(10.0) {
self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
}
This is also known as trailing closure( You can only do trailing closure if the closure parameter is the lastparameter)
这也称为尾随闭包(如果闭包参数是最后一个参数,则只能进行尾随闭包)
This doesn't mean the parameter 'animations' is no longer written. It is written but just as in the format of above.
这并不意味着不再写入参数“动画”。它是写的,但就像上面的格式一样。
Write exactly within the lines, most developers avoid such, because it's a little buggy to write with all the parenthesis and braces.
准确地写在行内,大多数开发人员都避免这样,因为用所有的括号和大括号来写有点麻烦。
UIView.animateWithDuration(10.0, animations: {
self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
})
(Contrary to trailing closure you wrote name ie 'animations') This is known as inline closure
(与尾随闭包相反,你写了名字,即“动画”)这被称为内联闭包
Write in a more modular sense
以更模块化的方式编写
UIView.animateWithDuration(duration: NSTimeInterval, animations: animatingFunc)
func animatingFunc() {
self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
}
Remember the type of the parameter 'animations' was () -> Void
记住参数“动画”的类型是 () -> Void
Exactly as what we are doing, animatingFunc takes no parameters ie '()' and returns nothing ie 'void'
与我们所做的完全一样,animatingFunc 不接受任何参数,即 '()' 并且不返回任何内容,即 'void'
(In Swift, functions are types and can be passed in as parameters) Some might say this is more readable some might say trailing closure is...
(在 Swift 中,函数是类型并且可以作为参数传入)有人可能会说这更易读有人可能会说尾随闭包是......
Side note1You can also do nothing ( which really doesn't make sense but in many other handlers/animations/completion handlers you may not want to do anything)
旁注1您也可以什么都不做(这确实没有意义,但在许多其他处理程序/动画/完成处理程序中,您可能不想做任何事情)
UIView.animateWithDuration(duration: NSTimeInterval, animations: nil)
Side note2
旁注2
Closures becomes more interesting when you have to capturea value. See thissimple demonstration. For more information about Swift closures see Apple's Documentation
回答by Zgpeace
How Do I Declare a Closure in Swift?
我如何在 Swift 中声明一个闭包?
As a variable:
var closureName: (ParameterTypes) -> ReturnType
As an optional variable:
var closureName: ((ParameterTypes) -> ReturnType)?
As a type alias:
typealias ClosureType = (ParameterTypes) -> ReturnType
As a constant:
let closureName: ClosureType = { ... }
As a parameter to another function:
funcName(parameter: (ParameterTypes) -> ReturnType)
作为变量:
var closureName: (ParameterTypes) -> ReturnType
作为可选变量:
var closureName: ((ParameterTypes) -> ReturnType)?
作为类型别名:
typealias ClosureType = (ParameterTypes) -> ReturnType
作为常数:
let closureName: ClosureType = { ... }
作为另一个函数的参数:
funcName(parameter: (ParameterTypes) -> ReturnType)
Note:if the passed-in closure is going to outlive the scope of the method, e.g. if you are saving it to a property, it needs to be annotated with @escaping
.
注意:如果传入的闭包将超过方法的作用域,例如,如果您将其保存到属性,则需要使用@escaping
.
As an argument to a function call:
funcName({ (ParameterTypes) -> ReturnType in statements })
As a function parameter:
array.sorted(by: { (item1: Int, item2: Int) -> Bool in return item1 < item2 })
As a function parameter with implied types:
array.sorted(by: { (item1, item2) -> Bool in return item1 < item2 })
As a function parameter with implied return type:
array.sorted(by: { (item1, item2) in return item1 < item2 })
As the last function parameter:
array.sorted { (item1, item2) in return item1 < item2 }
As the last parameter, using shorthand argument names:
array.sorted { return $0 < $1 }
As the last parameter, with an implied return value:
array.sorted { $0 < $1 }
As the last parameter, as a reference to an existing function:
array.sorted(by: <)
As a function parameter with explicit capture semantics:
array.sorted(by: { [unowned self] (item1: Int, item2: Int) -> Bool in return item1 < item2 })
As a function parameter with explicit capture semantics and inferred parameters / return type:
array.sorted(by: { [unowned self] in return $0 < $1 })
作为函数调用的参数:
funcName({ (ParameterTypes) -> ReturnType in statements })
作为函数参数:
array.sorted(by: { (item1: Int, item2: Int) -> Bool in return item1 < item2 })
作为具有隐含类型的函数参数:
array.sorted(by: { (item1, item2) -> Bool in return item1 < item2 })
作为具有隐含返回类型的函数参数:
array.sorted(by: { (item1, item2) in return item1 < item2 })
作为最后一个函数参数:
array.sorted { (item1, item2) in return item1 < item2 }
作为最后一个参数,使用速记参数名称:
array.sorted { return $0 < $1 }
作为最后一个参数,带有隐含的返回值:
array.sorted { $0 < $1 }
作为最后一个参数,作为对现有函数的引用:
array.sorted(by: <)
作为具有显式捕获语义的函数参数:
array.sorted(by: { [unowned self] (item1: Int, item2: Int) -> Bool in return item1 < item2 })
作为具有显式捕获语义和推断参数/返回类型的函数参数:
array.sorted(by: { [unowned self] in return $0 < $1 })
This site is not intended to be an exhaustive list of all possible uses of closures.
ref: http://goshdarnclosuresyntax.com/
该站点并非旨在详尽列出闭包的所有可能用途。
参考:http: //goshdarnclosuresyntax.com/