简单的问题,所以希望有一个简单的答案。您如何捕获/定义采用 var 参数的函数类型?
func foo(a:Int) -> Int {
return a + 1
}
func bar(var a:Int) -> Int {
return ++a
}
// define function type taking a constant parameter like foo above
typealias Foo = (Int)->Int
// try to a function type taking a var parameter like bar above
typealias Bar = (var Int)->Int
// gives a misleading compiler error about needing a leading semi colon
这看起来像是一个编译器错误,还是我遗漏了一些明显的东西?我正在使用 Xcode 6.1.1。
最佳答案
var
对参数的影响在函数的实现内部。因为它对函数的调用者没有影响,所以它不是函数签名/类型的一部分。
因此,您的函数 bar
与函数 foo
属于同一类型,也就是您将其别名为 Foo
的类型。
请注意,您的函数 bar
不会修改传递给它的值:
var num = 1
bar(num) // -> 2
num // -> 1
如果这就是您要查找的内容,那么您真正需要的是一个 inout
参数。那确实修改了函数语义,所以它是函数签名的一部分:
func baz(inout a: Int) -> Int {
return a++
}
typealias Baz = (inout Int)->Int
let b: Baz = baz
var num = 1
b(&num) // -> 1 (return from before the post-increment)
num // -> 2
关于ios - Swift:如何声明采用可变/var 参数的函数签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27929108/