0
我真的不確定爲什麼JSON解析會導致SIGABRT錯誤。Playground執行錯誤:解析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
}
好的,你認爲我應該做些什麼改變才能解決這個問題? –
我會爲您的枚舉添加一個構造函數,它接受一個字符串並返回一個正確創建的枚舉值。然後你可以調用類似'self.state = Bug.State(fromString:dict [「state」])' –
雖然我不認爲這是個問題。所有這三個self.xxx語句都會導致此錯誤。 –