编辑更新:
Swift 5或更高版本
extension RangeReplaceableCollection { mutating func rotate(positions: Int) { let index = self.index(startIndex, offsetBy: positions, limitedBy: endIndex) ?? endIndex let slice = self[..<index] removeSubrange(..<index) insert(contentsOf: slice, at: endIndex) }}extension RangeReplaceableCollection where Self: BidirectionalCollection { mutating func rotate(positions: Int, size: Int) { let index = self.index(startIndex, offsetBy: positions, limitedBy: endIndex) ?? endIndex let end = self.index(index, offsetBy: size - positions, limitedBy: self.index(before: endIndex)) ?? endIndex replaceSubrange(..<index, with: self[..<index].reversed()) replaceSubrange(index..<end, with: self[index..<end].reversed()) replaceSubrange(..<end, with: self[..<end].reversed()) }}var test = [1,2,3,4,5,6,7,8,9,10]test.rotate(positions: 3) // [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]var test2 = "1234567890"test2.rotate(positions: 3) // "4567890123"



