You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift如何替换数组中所有匹配的指定元素?

数组全量匹配元素替换方案

Swift 原生没有提供直接替换所有匹配元素的系统方法,可以通过以下两种常用方式实现需求:

方案1:使用map高阶函数(写法最简洁,推荐)

适合绝大多数轻量使用场景,通过映射遍历生成新数组完成替换:

var array = ["", "Orange", "Grape", "", "Apple", ""]
let resultArray = array.map { element in
    element == "" ? "Blank" : element
}
// 不需要保留原数组可直接覆盖赋值:array = array.map { ... }
print(resultArray) // 输出:["Blank", "Orange", "Grape", "Blank", "Apple", "Blank"]

方案2:原地遍历替换(适合大数组场景)

直接在原数组上修改,不需要额外开辟内存存储新数组,性能更好:

var array = ["", "Orange", "Grape", "", "Apple", ""]
for index in array.indices where array[index] == "" {
    array[index] = "Blank"
}
print(array) // 输出:["Blank", "Orange", "Grape", "Blank", "Apple", "Blank"]

通用扩展封装

可将逻辑封装为Array扩展,全局复用更方便:

extension Array where Element: Equatable {
    /// 替换数组中所有匹配的元素
    /// - Parameters:
    ///   - target: 需要替换的目标元素
    ///   - replacement: 替换后的内容
    mutating func replaceAll(_ target: Element, with replacement: Element) {
        for index in indices where self[index] == target {
            self[index] = replacement
        }
    }
}

// 调用示例
var testArray = ["", "Banana", "", "Cherry"]
testArray.replaceAll("", with: "Blank")
print(testArray) // 输出:["Blank", "Banana", "Blank", "Cherry"]

内容的提问来源于stack exchange,提问作者Rem Biths Wind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:45:06