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

Swift如何将Int数组的值动态替换字典字符串中的对应占位值

Swift 按顺序替换字符串占位符为数组对应值

你的模板字符串本身不是严格合法的JSON结构(存在字典未闭合、多余逗号的语法问题),直接做字符串替换是成本最低、最稳妥的实现方案,以下提供两种可直接运行的实现:


方案1:简单顺序替换(适用占位符严格按value1/value2...顺序排列的场景)

代码逻辑最简单,性能最高,只要你的模板占位符是从value1开始连续顺序排布,就可以直接用:

import Foundation

// 原始输入
var intArr = [1,2,3,4]
var dictString = "[{\"id\": value1, {\"id\":value2,}, {\"id\":value3}, {\"id\":value4}]"

// 遍历数组依次替换对应占位符
for (index, targetNum) in intArr.enumerated() {
    let placeholder = "value\(index + 1)" // 占位符从1开始编号,和数组0索引做偏移
    dictString = dictString.replacingOccurrences(of: placeholder, with: "\(targetNum)")
}

// 验证输出
print(dictString)
// 输出结果:[{"id": 1, {"id":2,}, {"id":3}, {"id":4}]

方案2:正则精准匹配替换(适用占位符顺序不固定、需要容错的场景)

如果你的模板里占位符可能打乱顺序,或者存在其他以value开头的字符串,用正则做精准匹配可以避免误替换,还能自动校验数组索引防止越界:

import Foundation

// 原始输入
var intArr = [1,2,3,4]
var dictString = "[{\"id\": value1, {\"id\":value2,}, {\"id\":value3}, {\"id\":value4}]"

do {
    // 正则匹配所有value+数字格式的占位符
    let placeholderRegex = try NSRegularExpression(pattern: "value(\\d+)")
    let allMatches = placeholderRegex.matches(
        in: dictString,
        range: NSRange(dictString.startIndex..., in: dictString)
    )
    // 倒序替换避免替换后字符串位置偏移导致匹配错误
    for match in allMatches.reversed() {
        // 提取占位符里的数字序号
        guard let numRange = Range(match.range(at: 1), in: dictString),
              let placeholderSeq = Int(dictString[numRange]) else { continue }
        // 转换为数组索引,校验索引合法性防止越界
        let arrIndex = placeholderSeq - 1
        guard intArr.indices.contains(arrIndex) else { continue }
        // 执行替换
        dictString = placeholderRegex.stringByReplacingMatches(
            in: dictString,
            range: match.range,
            withTemplate: "\(intArr[arrIndex])"
        )
    }
    // 验证输出
    print(dictString)
    // 输出结果:[{"id": 1, {"id":2,}, {"id":3}, {"id":4}]
} catch {
    print("正则初始化错误:\(error.localizedDescription)")
}

补充提醒:如果后续你需要把最终字符串转为合法JSON使用,需要先修正原始模板的语法问题——每个字典对象需要正确闭合},多余的尾部逗号需要删除,否则JSON解析会失败。

内容的提问来源于stack exchange,提问作者Duc Dang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 01:24:22