Swift 拼接 JSON 字符串

使用 #

1
2
3
4
5
6
7
8
9
let string = "{\"key1\": \"value\", \"key2\": 123}"
print(string) /// {"key1": "value", "key2": 123}

let string2 = #"{"key1": "value", "key2": 123}"#
print(string2) /// {"key1": "value", "key2": 123}

let value = 5
let string3 = #"{"key1": \#(value), "key2": 123}"#
print(string3) /// {"key1": 5, "key2": 123}
  1. Swift 开发:优雅处理转义字符必定用到小技巧,OC 可没有此福利
  2. 在 Swift 5 中如何使用原始字符串
  3. Why I cannot use \ or backslash in a String in Swift?

使用 “””

1
2
3
4
5
let jsonString = "[\"one\",\"two\",\"three\"]"

let jsonString = """
["one","two","three"]
"""
  1. How to parse array of strings in swift?

Swift 拼接 JSON 字符串
https://wonderhoi.com/2024/12/09/Swift-拼接-JSON-字符串/
作者
wonderhoi
发布于
2024年12月9日
许可协议