Swift & JSON: Unterschied zwischen den Versionen
Aus Wikizone
(Die Seite wurde neu angelegt: „== Beispiel == <syntaxhighlight lang="swift"> func parseJSON(weatherData: Data) { let decoder = JSONDecoder() // decode needs a type not an obj…“) |
|||
| Zeile 1: | Zeile 1: | ||
| + | == Links == | ||
| + | [[Swift - Snippets]] | ||
| + | [[Swift (Programmiersprache)]] | ||
| + | |||
== Beispiel == | == Beispiel == | ||
<syntaxhighlight lang="swift"> | <syntaxhighlight lang="swift"> | ||
Version vom 19. Januar 2023, 11:52 Uhr
Links
Swift - Snippets Swift (Programmiersprache)
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)")
}
}