let colorArray = [
UIColor.redColor(),
UIColor.orangeColor(),
UIColor.yellowColor(),
UIColor.greenColor(),
UIColor.blueColor()
]
Run Code Online (Sandbox Code Playgroud)
目标是转移阵列:
如果我们想要以橙色(原始数组中索引1处的颜色)开始,则数组将如下所示:
let colorArray = [
UIColor.orangeColor(),
UIColor.yellowColor(),
UIColor.greenColor(),
UIColor.blueColor(),
UIColor.redColor(),
]
Run Code Online (Sandbox Code Playgroud)
如果我们想要以绿色(原始数组中索引3处的颜色)开始,则数组将如下所示:
let colorArray = [
UIColor.greenColor(),
UIColor.blueColor(),
UIColor.redColor(),
UIColor.orangeColor(),
UIColor.yellowColor()
]
Run Code Online (Sandbox Code Playgroud)
我知道这可能会迟到.但是旋转或移动阵列最简单的方法是
func shifter(shiftIndex: Int) {
let strArr: [String] = ["a","b","c","d"]
var newArr = strArr[shiftIndex..<strArr.count]
newArr += strArr[0..<shiftIndex]
println(newArr) }
shifter(2) //[c, d, a, b] you can modify the function to take array as input
Run Code Online (Sandbox Code Playgroud)
我想出了简短的Swift 3和4解决方案:
extension Array {
func shifted(by shiftAmount: Int) -> Array<Element> {
// 1
guard self.count > 0, (shiftAmount % self.count) != 0 else { return self }
// 2
let moduloShiftAmount = shiftAmount % self.count
let negativeShift = shiftAmount < 0
let effectiveShiftAmount = negativeShift ? moduloShiftAmount + self.count : moduloShiftAmount
// 3
let shift: (Int) -> Int = { return $0 + effectiveShiftAmount >= self.count ? $0 + effectiveShiftAmount - self.count : $0 + effectiveShiftAmount }
// 4
return self.enumerated().sorted(by: { shift($0.offset) < shift($1.offset) }).map { $0.element }
}
}
Run Code Online (Sandbox Code Playgroud)
说明:
$0
元素的索引()并通过添加在步骤2中计算出的量来返回已移动的索引来准备实际的移位。如果新的索引落在数组长度之外,则需要将其包裹在最前面。enumerated()
给我们提供了一个元组数组[(offset: Int, element: Int)]
,它只是每个元素和元素本身的原始索引。然后,offset
通过应用步骤3中的函数,通过操作(即元素的索引)对枚举数组进行排序。最后,通过将排序后的元素映射回数组,从而摆脱了枚举。此扩展适用于任何类型的数组。例子:
let colorArray = [
UIColor.red,
UIColor.orange,
UIColor.yellow,
UIColor.green,
UIColor.blue
]
let shiftedColorArray = [
UIColor.green,
UIColor.blue,
UIColor.red,
UIColor.orange,
UIColor.yellow
]
colorArray.shifted(by: 2) == shiftedColorArray // returns true
[1,2,3,4,5,6,7].shifted(by: -23) // returns [3,4,5,6,7,1,2]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6355 次 |
最近记录: |