问题
Im trying to parse json in weather app, but have hit a snag that i cannot get past.
I do get an error, "Type 'int' does not conform to Protocol 'StringLiteralConvertible'" in the following code. Ive tried casting the jsonResult["main"] but that does instead give the error "Operand of postfix should have optional type, type is AnyObject". Do i need to downcast the Array in some way and how, if so, should i do that? I´ve searched so much for this but could not find any help in other posts. Code as follows.
func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
Alamofire.request(.GET, AlongRequest)
.responseJSON { (_, _, JSON, error) in
println(JSON)
self.updateUISuccess(JSON as NSArray!)
}
}
func updateUISuccess(jsonResult: NSArray) {
self.loading.text = nil
self.loadingIndicator.hidden = true
self.loadingIndicator.stopAnimating()
if let tempResult = ((jsonResult["main"] as NSArray)["temp"] as? Double)
回答1:
This would be easier to give a definitive answer to if you provide the JSON that you're trying to parse, but the error message you're getting is clear.
That error is because you're trying to access what you've declared as an NSArray
instance with a string subscript, twice in this one line:
if let tempResult = ((jsonResult["main"] as NSArray)["temp"] as? Double)
jsonResult
is declared as an NSArray
parameter, and then you're casting jsonResult["main"]
to NSArray
before trying to subscript it with ["temp"]
. The problem here is that NSArray
(and built-in Swift arrays) only use integer-based subscripting. The error is saying that where the Swift compiler is expecting an Int
, you've provided a string literal.
To fix this, you'll need to go in one of two directions. If the structure you're trying to access actually has these string keys, then you should be using NSDictionary
instead of NSArray
in both cases. If not, and it's an integer-index array, you should be using integers.
来源:https://stackoverflow.com/questions/26319350/int-does-not-conform-to-protocol-stringliteralconvertible