我将Objective-C应用程序重写为Swift,并面临将此Objective-C代码转换为Swift的问题。
Objective-C代码:
for ( void(^block)(void) in enumerator.allObjects) {
if (block)
block();
}
Swift Code:
for (var block: () -> Void in enumerator.allObjects) {
if (block) {
block();
}
}
Xcode显示3个错误:
预期表达
''中的预期条件声明
预期';'在'为'声明
非常感谢; - )
答案 0 :(得分:0)
取出括号
1> for i in 1...3 {
2. println(i)
3. }
1
2
3
4> for (i in 1...3) {
5. println(i)
6. }
repl.swift:4:8: error: expected ';' in 'for' statement
for (i in 1...3) {
^
repl.swift:4:8: error: expected condition in 'for' statement
for (i in 1...3) {
^
repl.swift:4:8: error: expected ';' in 'for' statement
for (i in 1...3) {
^
repl.swift:4:8: error: expected expression
for (i in 1...3) {
^
repl.swift:4:8: error: expected ')' in 'for' statement
for (i in 1...3) {
^
repl.swift:4:5: note: to match this opening '('
for (i in 1...3) {
^
repl.swift:4:8: error: expected '{' in 'for' statement
for (i in 1...3) {
^
repl.swift:4:18: error: statement cannot begin with a closure expression
for (i in 1...3) {
^
repl.swift:4:18: note: explicitly discard the result of the closure by assigning to '_'
for (i in 1...3) {
^
_ =
repl.swift:4:18: error: braced block of statements is an unused closure
for (i in 1...3) {
^
4>
答案 1 :(得分:0)
这很有效。
let block1 : (Int)->() = { i in
println(i)
}
let block2 : (Int)->() = { i in
println(i*2)
}
let array = [block1, block2]
for block in array {
block(1)
}