gpt4 book ai didi

ios - 无法从 Observable 对象中提取数据

转载 作者:行者123 更新时间:2023-11-29 05:09:58 25 4
gpt4 key购买 nike

我正在尝试显示来自观察对象的数据。

最初,我试图保持简单,仅显示结构的一个成员:“base”(值:“stations”)。

struct Sample: Codable {
let coord: Coord
let weather: [Weather]
let base: String
let main: Main
let visibility: Int
let wind: Wind
let clouds: Clouds
let dt: Double
// let sys: Sys
let id: Int
let name: String
// let cod: Int
}

我用“?”做了一些防御性编码但我收到以下编译器错误:

enter image description here

所以我替换了“?”与“!”,知道我应该有一些数据。

enter image description here

我发现这令人沮丧,因为它来自命令式范式背景。
我做错了什么?

这是数据转储:

Sample(coord: DataTaskPubTab.Coord(lon: -0.13, lat: 51.51), weather: [DataTaskPubTab.Weather(id: 300, main: "Drizzle", description: "light intensity drizzle")], base: "stations", main: DataTaskPubTab.Main(temp: 280.32, pressure: 1012, humidity: 81, tempMin: 279.15, tempMax: 281.15), visibility: 10000, wind: DataTaskPubTab.Wind(speed: 4.1, deg: 80), clouds: DataTaskPubTab.Clouds(all: 90), dt: 1485789600.0, id: 2643743, name: "London")

这是可观察对象:

class StandardWeatherReportLoader: ObservableObject {
@Published var networkMessage: String?
@Published var hasAlert = false
@Published var weatherReport: Sample?
@Published var hasReport = false

func doStandard() {
let url = EndPoint.weather.path()
var request = URLRequest(url: EndPoint.weather.path()!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let task = URLSession.shared.dataTask(with: url!) { (data: Data?, _: URLResponse?, error: Error?) -> Void in
DispatchQueue.main.async {
guard error == nil else {
self.networkMessage = error?.localizedDescription
self.hasAlert = true
return
}

do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(Sample.self, from: data!)
self.weatherReport = result
self.hasReport = true
print(result)
} catch let error as NSError {
print(error)
}
}
}
task.resume()
}
}

最佳答案

显然这有效:

struct StandardWeatherView: View {
@EnvironmentObject var settings: Settings
@ObservedObject var standardWeatherReportLoader = StandardWeatherReportLoader()

init() {
self.standardWeatherReportLoader.doStandard()
}

var body: some View {
NavigationView {
ZStack {
Color("FernGreen").edgesIgnoringSafeArea(.all)
VStack {
if standardWeatherReportLoader.weatherReport?.base == nil {
Text("Sorry, NO data.")
} else {
Text(standardWeatherReportLoader.weatherReport!.base)
}

Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
.navigationBarTitle(Text("Weather Report"), displayMode: .inline)
}.alert(isPresented: $standardWeatherReportLoader.hasAlert, content: { () -> Alert in
Alert(title: Text(verbatim: standardWeatherReportLoader.networkMessage!))
})
}
}
}

enter image description here

关于ios - 无法从 Observable 对象中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59779479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com