以下代码段的第二行会返回错误,除非我将读取"的部分更改为NSNumber" to" as String"。 rowData [" lngID"]中返回的值是一个数值。有人可以向我解释一下吗?
let rowData: NSDictionary = objReport as NSDictionary
let lngReportID = rowData["lngID"] as NSNumber
我在这里尝试做的是获取JSON响应并将其加载到对象数组中,如下所示。也许有更好的方法来实现这一目标。我们非常感谢任何有关更好方法的建议。首先,函数didReceiveAPIResults将结果返回给app。然后调用函数loadReportsIntoArray。
func loadReportsIntoArray(pReports: NSArray) {
arrayPoints = []
for (intRow, objReport) in enumerate(pReports) {
// index is the index within the array
// participant is the real object contained in the array
let rowData: NSDictionary = objReport as NSDictionary
let lngReportID = rowData["lngID"] as NSNumber
let lngReportTypeID = rowData["lngTypeID"] as NSNumber
let strOtherTypeName = rowData["strOtherTypeName"] as String
let strDescription = rowData["strDescription"] as String
let dtmFirstReport = rowData["dtmFirstReport"] as String
let dblLat = rowData["dblLat"] as NSNumber
let dblLong = rowData["dblLong"] as NSNumber
let strReportedByUsername = rowData["strReportedByUsername"] as String
let lngReportedByID = rowData["lngReportedBy"] as NSNumber
let lngCommentCount = rowData["lngCommentCount"] as NSNumber
let lngNumLikes = rowData["lngNumLikes"] as NSNumber
let blnUserLikedEvent = rowData["blnUserLikedEvent"] as Bool
var objReport = Report(plngReportID: lngReportID, plngReportTypeID: lngReportTypeID, pstrOtherTypeName: strOtherTypeName, pstrDescription: strDescription, pdtmFirstReport: dtmFirstReport, pdblLat: dblLat, pdblLong: dblLong, pstrReportedByUsername: strReportedByUsername, plngReportedByID: lngReportedByID, plngCommentCount: lngCommentCount, plngNumLikes: lngNumLikes, pblnUserLikedEvent: blnUserLikedEvent)
//arrayPoints.append(objReport)
}
}
func didReceiveAPIResults(results: NSDictionary) {
var success: NSInteger = results["success"] as NSInteger
if success == 1 {
var resultsArr = results["geopoints"] as NSArray
dispatch_async(dispatch_get_main_queue(), {
self.loadReportsIntoArray(resultsArr)
})
}
else {
// Error occurred
}
}
答案 0 :(得分:1)
我可以使用以下代码重新创建错误:
let objReport = NSDictionary(object: "string", forKey: "lngID")
let rowData: NSDictionary = objReport as NSDictionary
let lngReportID = rowData["lngID"] as NSNumber // Error
但是,将objReport
更改为NSDictionary(object: NSNumber(integer: 0), forKey: "lngID")
可以解决问题。因此,我认为您的问题是为密钥lngID
存储的对象不是NSNumber
。
对于解决方案,你应该看看Kumar Nitin的回答,检查你是否有一个存储过的号码,或者你可以使用这些代码,他们都做了同样的事情:
if let lngID = rowData["lngID"] as? NSNumber {
// Do stuff with lngID.
}
答案 1 :(得分:0)
在swift中,你没有NSNumber,但是如果需要你可以使用Obj C的NSNumber。
如果您期望double或float或int,则上面的NSNumber代码应如下所示。添加一项检查以确保该值不为零,否则会导致您的应用崩溃。
if let lngReportID = rowData["lngID"] as? Int {
//Do the task required
}