【发布时间】:2017-05-04 19:32:54
【问题描述】:
我真的不确定为什么 JSON 解析会导致 SIGABRT 错误。
class Bug {
enum State {
case open
case closed
}
let state: State
let timestamp: Date
let comment: String
init(state: State, timestamp: Date, comment: String) {
self.state = state
self.timestamp = timestamp
self.comment = comment
}
init(jsonString: String) throws {
let dict = convertToDictionary(from: jsonString)
我认为这是导致错误的原因,但我无法弄清楚原因:
self.state = dict["state"] as! Bug.State
self.comment = dict["comment"] as! String
self.timestamp = dict["timestamp"] as! Date
}
}
JSON 字符串到字典:
func convertToDictionary(from text: String) -> [String: Any] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any? = try? JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: Any] ?? [:]
}
enum TimeRange {
case pastDay
case pastWeek
case pastMonth
}
【问题讨论】: