我在为WidgetKit找到合适的占位符时遇到了麻烦。我遇到的问题是,我不确定如何设置Codable数据的默认值,我尝试过,但它没有在我的占位符视图中显示任何数据。我希望我的占位符显示每小时和每天的Codable数据,但使用默认值。
然后这是我在小部件中的占位符
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), weather: Weather(current: Current(symbol: "n200", symbolPhrase: "partly cloudy", windSpeed: 0)), hourly: Hourly(forecast: [Hour]()), daily: Daily(forecast: [Day]()))
}struct Day: Codable {
let date: String
let symbol: String
let symbolPhrase: String
let maxWindSpeed: Int
enum CodingKeys: String, CodingKey {
case date, symbol, symbolPhrase, maxWindSpeed
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
date = try container.decode(String?.self, forKey: .date) ?? "2020-03-16"
symbol = try container.decode(String?.self, forKey: .symbol) ?? "d320"
symbolPhrase = try container.decode(String?.self, forKey: .symbolPhrase) ?? "partly cloudy"
maxWindSpeed = try container.decode(Int?.self, forKey: .maxWindSpeed) ?? 0
}
}


发布于 2021-06-03 00:44:56
简单的解决方案,出于某种原因,它超出了我的理解。
Array(repeating: Hour(time: "2020-03-16T14:00+01:00", symbol: "n200" , symbolPhrase: "partly cloudy", windSpeed: 0), count: 5)

https://stackoverflow.com/questions/67769098
复制相似问题