enumerateLinesSwift String类型的函数声明如下:
enumerateLines(body: (line: String, inout stop: Bool) -> ())
Run Code Online (Sandbox Code Playgroud)
据我了解,这个声明表示:"enumerateLines是一个函数采取关闭,body,这是交给两个变量,line和stop,并返回void."
根据Swift编程语言书,我相信我应该能够以enumerateLines一个简洁的简洁方式调用尾随闭包,如下所示:
var someString = "Hello"
someString.enumerateLines()
{
// Do something with the line here
}
Run Code Online (Sandbox Code Playgroud)
..但是会导致编译错误:
Tuple types '(line: String, inout stop: Bool)' and '()' have a different number of elements (2 vs. 0)
那么我尝试显式地放入参数,并取消尾随闭包:
addressString.enumerateLines((line: String, stop: Bool)
{
// Do something with the line here
})
Run Code Online (Sandbox Code Playgroud)
...但是会导致错误:
'(() -> () -> $T2) -> $T3' is not identical to '(line: String.Type, stop: Bool.Type)'
简而言之,我尝试过的语法没有导致任何可以成功编译的语法.
任何人都可以在我的理解中指出错误并提供一个可行的语法吗?我正在使用Xcode 6 Beta 4.
Mar*_*n R 12
所述闭合表达式语法具有一般形式
{ (parameters) -> return type in
statements
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下:
addressString.enumerateLines ({
(line: String, inout stop: Bool) -> () in
println(line)
})
Run Code Online (Sandbox Code Playgroud)
或者,使用尾随闭包语法:
addressString.enumerateLines {
(line: String, inout stop: Bool) in
println(line)
}
Run Code Online (Sandbox Code Playgroud)
由于自动类型推断,这可以缩短为
addressString.enumerateLines {
line, stop in
println(line)
}
Run Code Online (Sandbox Code Playgroud)
Swift 3更新:
addressString.enumerateLines { (line, stop) in
print(line)
// Optionally:
if someCondition { stop = true }
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您不需要"停止"参数:
addressString.enumerateLines { (line, _) in
print(line)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2315 次 |
| 最近记录: |