Ric*_*hiy 13 arrays generics ios swift
给定n个元素的数组,即
var array = [1, 2, 3, 4, 5]
我可以写一个扩展名,Array
所以我可以修改数组来实现这个输出[2, 3, 4, 5, 1]
:
mutating func shiftRight() {
append(removeFirst())
}
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这样一个函数,可以通过任何索引,正面或负面移动数组.我可以使用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])
}
}
Run Code Online (Sandbox Code Playgroud)
Nat*_*ook 24
您可以使用远程订阅并连接结果.这将为您提供所需的名称,其名称与标准库类似:
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, 3, 4, 5, 6, 7, 8, 9, 10, 1]
Array(1...10).shiftRight(7)
// [8, 9, 10, 1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
取而代之的下标,你也可以返回Array(suffix(count - amount) + prefix(amount))
从shiftRight()
.
Ima*_*tit 18
使用Swift 3,您只需几行代码即可创建shift(withDistance:)
和创建shiftInPlace(withDistance:)
方法:
extension Array {
func shift(withDistance distance: Int = 1) -> Array<Element> {
let offsetIndex = distance >= 0 ?
self.index(startIndex, offsetBy: distance, limitedBy: endIndex) :
self.index(endIndex, offsetBy: distance, limitedBy: startIndex)
guard let index = offsetIndex else { return self }
return Array(self[index ..< endIndex] + self[startIndex ..< index])
}
mutating func shiftInPlace(withDistance distance: Int = 1) {
self = shift(withDistance: distance)
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
let array = Array(1...10)
let newArray = array.shift(withDistance: 3)
print(newArray) // prints: [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)