
var array = [1,2,3,4,5]
我可以写一个扩展到Array,所以我可以修改数组来实现这个输出:[2,5,1]:
mutating func shiftRight() { append(removeFirst()) } 有没有办法实现这样的功能,可以通过任何索引(正或负)来移动数组.我可以用if-else子句强制执行这个功能,但是我正在寻找的是功能实现.
算法很简单:
>按提供的索引将数组拆分成两个
>将第一个数组追加到第二个数组的末尾
有没有什么办法实现它的功能风格?
我完成的代码:
extension Array { mutating func shift(var amount: Int) { guard -count...count ~= amount else { return } if amount < 0 { amount += count } self = Array(self[amount ..< count] + self[0 ..< amount]) }}解决方法 您可以使用范围下标并连接结果.这将给你你想要的,名称类似于标准库: extension Array { func shiftRight(var amount: Int = 1) -> [Element] { assert(-count...count ~= amount,"Shift amount out of bounds") if amount < 0 { amount += count } // this needs to be >= 0 return Array(self[amount ..< count] + self[0 ..< amount]) } mutating func shiftRightInPlace(amount: Int = 1) { self = shiftRight(amount) }}Array(1...10).shiftRight()// [2,6,7,8,9,10,1]Array(1...10).shiftRight(7)// [8,1,7] 您也可以从shiftRight()返回Array(后缀(count – amount)前缀(amount))而不是下标.
总结以上是内存溢出为你收集整理的ios – Swift:通过索引移动数组中的元素全部内容,希望文章能够帮你解决ios – Swift:通过索引移动数组中的元素所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)