★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝()➤GitHub地址:➤原文地址: ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★扩展Array
1 extension Array where Element : Equatable { 2 //获取数组中的指定元素的索引值 3 //Parameter item: 元素 4 //Returns: 索引值数组 5 public func indexes(_ item: Element) -> [Int] { 6 var indexes = [Int]() 7 for index in 0..Int? {17 for (index, value) in lazy.enumerated() where value == item {18 return index19 }20 return nil21 } 22 23 //获取元素最后出现的位置24 //Parameter item: 元素25 //Returns: 索引值26 public func lastIndex(_ item: Element) -> Int? {27 return indexes(item).last28 }29 30 //删除数组中的指定元素31 //Parameter object: 元素32 public mutating func remove(_ object:Element) -> Void {33 for idx in self.indexes(object).reversed() {34 self.remove(at: idx)35 }36 }37 }
测试代码:
1 var arr:[Int] = [1,2,3,4,5,5,6,7,7,8,9,10]2 print(arr.firstIndex(5))3 //Prnt Optional(4)4 print(arr.lastIndex(7))5 //Prnt Optional(8)6 arr.remove(7)7 print(arr)8 //Prnt [1, 2, 3, 4, 5, 5, 6, 8, 9, 10]
扩展数组,二分法插入:
1 private extension Array where Element: Comparable { 2 private func binarySearchIndex(for element: Element) -> Int { 3 var min = 0 4 var max = count 5 while min < max { 6 let index = (min+max)/2 7 let other = self[index] 8 if other == element { 9 return index10 } else if other < element {11 min = index+112 } else {13 max = index14 }15 }16 return min17 }18 19 mutating func binaryInsert(_ element: Element) {20 insert(element, at: binarySearchIndex(for: element))21 }22 }
测试代码:
1 var arr:[Int] = [1,2,3,4,5,6,7,8,9]2 arr.binaryInsert(5)3 print(arr)4 //Print [1, 2, 3, 4, 5, 5, 6, 7, 8, 9]