给定 JSON 数据:
{
"location": "Toronto, Canada",
"three_day_forecast": [
{
"conditions": "Partly cloudy",
"day" : "Monday",
"temperature": 20
},
{
"conditions": "Showers",
"day" : "Tuesday",
"temperature": 22
},
{
"conditions": "Sunny",
"day" : "Wednesday",
"temperature": 28
}
]
}
以及以下课程:
class WeatherResponse: Mappable {
var location: String?
var threeDayForecast: [Forecast]?
required init?(_ map: Map){
}
func mapping(map: Map) {
location <- map["location"]
threeDayForecast <- map["three_day_forecast"]
}
}
class Forecast: Mappable {
var day: String?
var temperature: Int?
var conditions: String?
required init?(_ map: Map){
}
func mapping(map: Map) {
day <- map["day"]
temperature <- map["temperature"]
conditions <- map["conditions"]
}
}
我在我的ViewController
:
class ViewController: UIViewController {
var threeDayForecastArray = [Forecast]()
override func viewDidLoad() {
super.viewDidLoad()
getWeatherReport()
print(threeDayForecastArray.count) // 0
print(threeDayForecastArray[0].conditions) //fatal error: Index out of range
}
func getWeatherReport() {
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
Alamofire.request(.GET, URL).responseObject { (response: Response<WeatherResponse, NSError>) in
let weatherResponse = response.result.value
print(weatherResponse?.location)
if let threeDayForecast = weatherResponse?.threeDayForecast {
self.threeDayForecastArray = threeDayForecast
for forecast in threeDayForecast {
print(forecast.day)
print(forecast.temperature)
}
}
}
}
}
我正在尝试填充threeDayForecastArray
,但它给了我 count = 0 或超出索引错误。欢迎任何关于我做错了什么的建议或帮助。