作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
考虑数组[1,2,3,4]
。如何将数组项重新排列到新位置。
例如:
将 3 放入位置 4 [1,2,4,3]
将 4 放入位置 1 [4,1,2,3]
将 2 放入位置 3 [1,3,2,4]
。
最佳答案
let element = arr.remove(at: 3)
arr.insert(element, at: 2)
函数形式:
func rearrange<T>(array: Array<T>, fromIndex: Int, toIndex: Int) -> Array<T>{
var arr = array
let element = arr.remove(at: fromIndex)
arr.insert(element, at: toIndex)
return arr
}
这会将 3 放到位置 4。
let element = arr.removeAtIndex(3)
arr.insert(element, atIndex: 2)
你甚至可以做一个通用的函数:
func rearrange<T>(array: Array<T>, fromIndex: Int, toIndex: Int) -> Array<T>{
var arr = array
let element = arr.removeAtIndex(fromIndex)
arr.insert(element, atIndex: toIndex)
return arr
}
这里需要 var
arr
,因为如果不将输入参数指定为 in-out
,就无法改变输入参数。然而,在我们的例子中,我们得到了一个没有副作用的纯函数,在我看来,这更容易推理。然后你可以这样调用它:
let arr = [1,2,3,4]
rearrange(arr, fromIndex: 2, toIndex: 0) //[3,1,2,4]
关于arrays - 如何将数组的项目重新排列到 Swift 中的新位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36541764/
我是一名优秀的程序员,十分优秀!