gpt4 book ai didi

arrays - 如何将数组的项目重新排列到 Swift 中的新位置?

转载 作者:IT王子 更新时间:2023-10-29 04:59:18 24 4
gpt4 key购买 nike

考虑数组[1,2,3,4]。如何将数组项重新排列到新位置。

例如:

将 3 放入位置 4 [1,2,4,3]

将 4 放入位置 1 [4,1,2,3]

将 2 放入位置 3 [1,3,2,4]

最佳答案

swift 3.0+:

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
}

swift 2.0:

这会将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com