A.A*_*omi 4 swift swift-playground
我有以下简单的代码段:
func swapper(var arr: [Int]) {
let first: Int = arr[0]
let last: Int = arr[arr.count - 1]
arr[0] = last
arr[arr.count - 1] = first
arr
}
var myFunctionPointer : ([Int]) -> () = swapper
Run Code Online (Sandbox Code Playgroud)
它运行良好但是当我尝试将inout添加 到方法的参数的签名时,我无法将其分配给变量外部,如下所示.
func swapper(inout arr: [Int]){
let first: Int = arr[0]
let last: Int = arr[arr.count - 1]
arr[0] = last
arr[arr.count - 1] = first
arr
}
var myFunctionPointer: ([Int]) -> () = swapper // This failed [int] is not subtype of inout [Int]
var myFunctionPointer: (inout[Int]) -> () = swapper // I am not getting a compilation error, but the playground keeps showing an error message and everything stopped working
Run Code Online (Sandbox Code Playgroud)
我正在使用Xcode 6.1 Playground.
第二种方式是正确的方式,但Xcode有一个错误?有什么想法吗?
这似乎是操场上的一个错误.它在没有问题的项目中工作.
它可以简化(我意识到这可能不是你真正的代码,但它提供了一个更好的方法的好例子):
func swapper(inout arr: [Int]){
(arr[0], arr[arr.count - 1]) = (arr[arr.count - 1], arr[0])
}
//let myFunctionPointer : (inout [Int])->Void = swapper
let myFunctionPointer = swapper // There's no real reason for a type here
var x = [1,2,3]
myFunctionPointer(&x)
println(x)
Run Code Online (Sandbox Code Playgroud)
请注意,放在arr函数末尾不是一个好习惯.Swift不返回计算的最后一个值,因此该行根本不做任何事情(但会产生一些混淆).
编辑:实际上,它甚至可以比这更简单(我没有意识到这会工作,直到我尝试它):
func swapper(inout arr: [Int]){
swap(&arr[0], &arr[arr.count-1])
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6159 次 |
| 最近记录: |