在 Playgrounds 中,以下代码会产生错误:
import Foundation
struct Model: Codable {
let textBody: String
enum CodingKeys: String, CodingKey {
case textBody = "TextBody"
}
}
let json = """
{
"TextBody": "First Line\n\nLastLine"
}
""".data(using: .utf8)!
let model = try! JSONDecoder().decode(Model.self, from: json)
Run Code Online (Sandbox Code Playgroud)
致命错误:“尝试!” 表达式意外引发错误: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.",underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control字符 27 周围的字符。” UserInfo={NSDebugDescription=字符 27 周围的未转义控制字符。}))):文件 MyPlayground.playground,第 19 行
根据 JSONLint,上面的 JSON 是完全有效的。那么什么给呢?
更新:
我需要一个解决方案来处理从 API 返回的数据。这是我到目前为止想出的东西,但它很糟糕......
if let data = data,
let …Run Code Online (Sandbox Code Playgroud) 使用以下OptionSet:
struct StatusOptions : OptionSet {
let rawValue: Int
static let CountdownDuration0 = StatusOptions(rawValue: 1 << 0)
static let CountdownDuration1 = StatusOptions(rawValue: 1 << 1)
static let CountdownDuration2 = StatusOptions(rawValue: 1 << 2)
static let CountdownDuration3 = StatusOptions(rawValue: 1 << 3)
static let CountdownDuration4 = StatusOptions(rawValue: 1 << 4)
static let CountdownDuration5 = StatusOptions(rawValue: 1 << 5)
static let HomeMode = StatusOptions(rawValue: 1 << 6)
static let AwayMode = StatusOptions(rawValue: 1 << 7)
static let Disarmed: StatusOptions = []
static …Run Code Online (Sandbox Code Playgroud)