【发布时间】:2018-08-08 18:29:04
【问题描述】:
我试图使用 swift 4 和 openWeather API 构建一个天气应用程序,但我卡在了这个函数中:
func fetchWeather(){
let weatherGetter = GetWeather()
self.cityWeather = [Temperature]()
for city in cities {
weatherGetter.getWeather(city: city) { (temp) in
guard let temp = temp else {return}
print(temp)
self.cityWeather?.append(temp)
}
}
print(self.cityWeather?.count)
self.collectionView?.reloadData()
}
所以这个函数在控制台中给了我这个
可选(0) 温度(城市:“伦敦”,cityTemperature:“294.06”,tempIcon:“01d”) 温度(城市:“东京”,cityTemperature:“297.33”,tempIcon:“09n”) 温度(城市:“巴黎”,cityTemperature:“298.0”,tempIcon:“01d”) 温度(城市:“莫斯科”,cityTemperature:“291.41”,tempIcon:“01n”)
这对我来说真的很奇怪,因为 print(self.cityWeather?.count) 是在 for 循环之后使用的,但在控制台中 Optional(0) 是第一位的。
所以如果我用这个方法
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cityWeather?.count ?? 0
}
我的集合视图单元格不会显示,因为它返回 0。
但是如果在 self.cityWeather?.append(temp) 之后使用 print(self.cityWeather) 我明白了! (我删除了所有其他打印语句):
可选([WhatsWeather.Temperature(city: "Moscow", cityTemperature: "291.41", tempIcon: "01n")]) 可选([WhatsWeather.Temperature(城市:“莫斯科”,cityTemperature:“291.41”,tempIcon:“01n”),WhatsWeather.Temperature(城市:“伦敦”,cityTemperature:“294.05”,tempIcon:“01d”)]) 可选([WhatsWeather.Temperature(城市:“莫斯科”,cityTemperature:“291.41”,tempIcon:“01n”),WhatsWeather.Temperature(城市:“伦敦”,cityTemperature:“294.05”,tempIcon:“01d”),WhatsWeather .Temperature(城市:“巴黎”,cityTemperature:“298.0”,tempIcon:“01d”)]) 可选([WhatsWeather.Temperature(城市:“莫斯科”,cityTemperature:“291.41”,tempIcon:“01n”),WhatsWeather.Temperature(城市:“伦敦”,cityTemperature:“294.05”,tempIcon:“01d”),WhatsWeather .Temperature(city: "Paris", cityTemperature: "298.0", tempIcon: "01d"), WhatsWeather.Temperature(city: "Tokyo", cityTemperature: "297.38", tempIcon: "09n")])
【问题讨论】:
-
count逻辑存在缺陷,请查看更新后的答案。 -
@rakesha-shastri 谢谢你的帮助!
标签: swift xcode dictionary uicollectionview