2017-05-04 20 views
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 
} 

錯誤圖像:enter image description here

回答

2

此行似乎是一個問題:

self.state = dict["state"] as! Bug.State

Bug.Stateenum自定義類型。但是dict["state"]的值是String。通過使用as!你是在告訴你知道編譯器將是一個Bug.State在運行,但是當系統中的應用程序運行時,看起來它發現它是一個字符串,它是一個Bug.State所以它拋出一個例外。

類似地,在設置時間戳的行上,您嘗試使用直接類型轉換將可能是字符串的內容轉換爲日期。您將不得不使用NSDateFormatter從字符串中提取日期以將該值轉換爲字符串。

+0

好的,你認爲我應該做些什麼改變才能解決這個問題? –

+0

我會爲您的枚舉添加一個構造函數,它接受一個字符串並返回一個正確創建的枚舉值。然後你可以調用類似'self.state = Bug.State(fromString:dict [「state」])' –

+0

雖然我不認爲這是個問題。所有這三個self.xxx語句都會導致此錯誤。 –