Swift 4.1、Xcode 9.3:为Array实现类似String的多替换扩展
Array 批量替换元素扩展实现
没问题!我来帮你把String的多替换扩展逻辑平移到Array上~核心就是批量匹配数组中的元素并替换成对应值,完全贴合你现有的String扩展使用习惯。
完整扩展代码
直接上实现代码,包含返回新数组和原地修改两个版本(和String的方法风格保持一致):
public extension Array where Element: Equatable { /// 将数组中多个指定元素的所有匹配项替换为对应的值 /// - Parameter replacements: 一组包含目标元素和替换值的元组,格式为(of: Element, with: Element) /// - Returns: 完成所有替换后的新数组 func replacingMultipleOccurrences(using replacements: (of: Element, with: Element)...) -> [Element] { var result = self for replacement in replacements { result = result.map { $0 == replacement.of ? replacement.with : $0 } } return result } /// 原地批量替换元素,直接修改原数组 /// - Parameter replacements: 一组包含目标元素和替换值的元组,格式为(of: Element, with: Element) mutating func replaceMultipleOccurrences(using replacements: (of: Element, with: Element)...) { self = replacingMultipleOccurrences(using: replacements) } }
代码细节说明
- 类型约束:给
Array加了Element: Equatable的约束,因为要判断元素是否匹配目标值,这是替换逻辑的基础;如果你的自定义类型需要用这个扩展,只要让类型遵循Equatable协议就行。 - 返回新数组的方法:
replacingMultipleOccurrences接收可变参数的替换规则元组,遍历每个规则,用map对数组元素逐个判断替换,最终返回新数组,不会修改原数组。 - 原地修改方法:
replaceMultipleOccurrences是mutating方法,直接调用上面的方法生成新数组并赋值给原数组,适合需要直接修改原数组的场景。
使用示例
基础类型场景
// 整数数组示例 var numbers = [1, 2, 3, 2, 4, 1] let newNumbers = numbers.replacingMultipleOccurrences(using: (of: 1, with: 10), (of: 2, with: 20)) print(newNumbers) // 输出: [10, 20, 3, 20, 4, 10] // 原地修改示例 numbers.replaceMultipleOccurrences(using: (of: 3, with: 30), (of: 4, with: 40)) print(numbers) // 输出: [10, 20, 30, 20, 40, 10]
自定义类型场景
enum Fruit: Equatable { case apple, banana, orange } var fruits = [Fruit.apple, .banana, .apple, .orange] let newFruits = fruits.replacingMultipleOccurrences(using: (of: .apple, with: .orange), (of: .banana, with: .apple)) print(newFruits) // 输出: [orange, apple, orange, orange]
内容的提问来源于stack exchange,提问作者Noah Wilder
相关产品推荐
相关产品推荐

