Skip to content

Commit

Permalink
Simplify the code in array.swift (krahets#960)
Browse files Browse the repository at this point in the history
* 简单点

* Apply suggestions from code review

Co-authored-by: nuomi1 <[email protected]>

---------

Co-authored-by: Yudong Jin <[email protected]>
Co-authored-by: nuomi1 <[email protected]>
  • Loading branch information
3 people authored Nov 23, 2023
1 parent 5b6fb34 commit c5e37c1
Showing 1 changed file with 2 additions and 3 deletions.
5 changes: 2 additions & 3 deletions codes/swift/chapter_array_and_linkedlist/array.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func extend(nums: [Int], enlarge: Int) -> [Int] {
/* 在数组的索引 index 处插入元素 num */
func insert(nums: inout [Int], num: Int, index: Int) {
// 把索引 index 以及之后的所有元素向后移动一位
for i in sequence(first: nums.count - 1, next: { $0 > index + 1 ? $0 - 1 : nil }) {
for i in nums.indices.dropFirst(index).reversed() {
nums[i] = nums[i - 1]
}
// 将 num 赋给 index 处元素
Expand All @@ -37,9 +37,8 @@ func insert(nums: inout [Int], num: Int, index: Int) {

/* 删除索引 index 处元素 */
func remove(nums: inout [Int], index: Int) {
let count = nums.count
// 把索引 index 之后的所有元素向前移动一位
for i in sequence(first: index, next: { $0 < count - 1 - 1 ? $0 + 1 : nil }) {
for i in nums.indices.dropFirst(index).dropLast() {
nums[i] = nums[i + 1]
}
}
Expand Down

0 comments on commit c5e37c1

Please sign in to comment.