Swift & JSON: Unterschied zwischen den Versionen
Aus Wikizone
(→Links) |
|||
| Zeile 2: | Zeile 2: | ||
[[Swift - Snippets]] | [[Swift - Snippets]] | ||
[[Swift (Programmiersprache)]] | [[Swift (Programmiersprache)]] | ||
| + | [[Swift - Möglichkeiten Daten zu speichern#Speichern von JSON Daten mit File I/O]] | ||
== Beispiel == | == Beispiel == | ||
Version vom 21. Januar 2023, 05:19 Uhr
Links
Swift - Snippets Swift (Programmiersprache) Swift - Möglichkeiten Daten zu speichern#Speichern von JSON Daten mit File I/O
Beispiel
func parseJSON(weatherData: Data) {
let decoder = JSONDecoder()
// decode needs a type not an object as parameter. We refer to the type with .self i.e. WeatherData.self
do {
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
let id = decodedData.weather[0].id
let temp = decodedData.main.temp
let name = decodedData.name
let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
print( "weatherName (sf-symbol): \(weather.conditionName)")
print( "temperature: \(weather.temperatureStr)")
} catch {
print("Error parsing JSON: \(error)")
}
}