我在使用swift 3中的inout参数进行编码时遇到此错误。 以下代码生成错误:
class Example {
var a : Int
init(_ a: Int) {
self.a=a
}
}
let closure = { val in val.a = 7 } as (inout Example) -> ()
var v = Example(6)
closure(&v)
控制台:
Playground execution failed: error: parameters may not have the 'var' specifier
* thread #1: tid = 0x12e365d, 0x00000001071d33c0 MyPlayground`executePlayground, queue = 'com.apple.main-thread', stop reason = breakpoint 1.2
* frame #0: 0x00000001071d33c0 MyPlayground`executePlayground
frame #1: 0x00000001071d29c0 MyPlayground`__37-[XCPAppDelegate enqueueRunLoopBlock]_block_invoke + 32
frame #2: 0x0000000107cee6ac CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
frame #3: 0x0000000107cd36f4 CoreFoundation`__CFRunLoopDoBlocks + 356
frame #4: 0x0000000107cd2e65 CoreFoundation`__CFRunLoopRun + 901
frame #5: 0x0000000107cd2884 CoreFoundation`CFRunLoopRunSpecific + 420
frame #6: 0x000000010d172a6f GraphicsServices`GSEventRunModal + 161
frame #7: 0x0000000108880c68 UIKit`UIApplicationMain + 159
frame #8: 0x00000001071d26e9 MyPlayground`main + 201
frame #9: 0x000000010b2b468d libdyld.dylib`start + 1
这段代码错了吗?这个错误来自哪里?它可能是编译器错误吗?
答案 0 :(得分:2)
看来你只想宣告一个()
- 返回一个带有自定义类型的inout
参数的闭包。为此,不需要使用类型转换(使用as
)来帮助编译器推断闭包的类型。
你可以(正如@Hamish所指出的那样)简单地在闭包体内注释inout
参数类型,这足以让编译器将闭包类型推断为(inout Example) -> ()
:
let closure = { (val: inout Example) in val.a = 7 }
或者,您可以显式地键入注释闭包的类型:
let closure: (inout Example) -> () = { val in val.a = 7 }
尽管如此,您的示例中的编译器错误是错误诊断,这可能值得提交错误。
似乎已经有一些错误报告,其中inout
参数使用导致的错误(在不同的上下文中)产生了离点混淆错误消息"参数可能没有' { {1}}'符&#34 ;;例如
提交错误报告,这个误诊也会在尝试如上所述声明闭包时显示(使用var
),这对于Swift团队来说可能是有价值的信息(额外的as
到关闭错误消息的情况),即使我们永远不想在你的例子的声明语境中使用inout
。正如@matt写的评论。
" Swift团队特别提到他们希望改进编译器错误消息。"