我的代码是
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSArray
let json = JSON(jsonData)
for (_, subJSON): (String, JSON) in json[0]["events"] {
let rel1 = InboxEvents(title: subJSON["title"].string!, guests: subJSON["guests"].string!, eventpic: subJSON["eventpic"].string!, eventID : NSInteger(subJSON["ID"].string!)!)
self.arrayOfRels.append(rel1)
}
这是InboxEvents
类
class InboxEvents {
var title = ""
var guests = ""
var eventpic = ""
var eventID = 6
init(title : String, guests: String, eventpic : String, eventID : NSInteger) {
self.title = title
self.guests = guests
self.eventpic = eventpic
self.eventID = eventID
}
我在for循环中有fatal error: unexpectedly found nil while unwrapping an Optional value
。
json输出在这里
[
{
"events" : [
{
"ID" : "3",
"title" : "Test Event",
"guests" : 3,
"eventpic" : "/images\/event_pic\/event1.jpg"
},
{
"ID" : "1",
"title" : "Test Event",
"guests" : 2,
"eventpic" : "/images\/event_pic\/event1.jpg"
}
]
}
]
这里有什么问题?
答案 0 :(得分:1)
您的问题出现在您显示的json中的DATEDIFF()
作为示例,guest参数是Int类型,但是当您获取值时,您将该值作为字符串获取
因此,当您只是打印该值时,它将显示为零,当您尝试强制打开时,它会崩溃
所以可以有两个选项
您将json guest属性更改为字符串,而不是将您作为字符串传递的InboxEvent
另一种选择是根据您的要求获取interger / dobule中的值将其转换为字符串并传入InboxEvent或使InboxEvent获取Int而不是字符串