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 またはインデックス不足エラーが発生します。私が間違っていることや助けについてのアドバイスは大歓迎です。