Swift - Computed Properties
Aus Wikizone
Links[Bearbeiten]
Swift (Programmiersprache)
Stored Properties vs. Computed Properties[Bearbeiten]
Die in Klassen und Structs enthaltenen Eigenschaften / Properties speichern die Daten mit denen man sie füllt. Deshalb nennt man sie auch Stored Properties.
Computed Properties gehen einen Schritt weiter. Sie enthalten eine eingebaute Funktion mit denen sie sich selber aktualisieren können. D.h. sie passen ihren Wert automatisch an, wenn sich z.B. andere Properties in der Klasse verändern.
Beispiel WeatherModel[Bearbeiten]
struct WeatherModel {
let conditionId: Int
let cityName: String
let temperature: Double
var conditionName: String{
/**
Computed Property which holds a sf-symbol name
When the conditionId changes the conditionName changes its value automatically
conditionId could be a weather code received from openWeather.org i.e.
*/
switch conditionId {
case 200...202:
return "cloud.bolt.rain.fill"
case 210...221:
return "cloud.bold."
case 230...299:
return "cloud.bold.rain"
case 300...399:
return "cloud.drizzle"
case 500...501:
return "cloud.rain"
case 502...599:
return "cloud.heavyrain"
case 600...699:
return "cloud.snow"
case 700...721:
return "sun.haze"
case 731...741:
return "cloud.fog"
case 751...762:
return "sun.dust"
case 771...781:
return "tornado"
case 800:
return "sun.max"
case 801...802:
return "cloud"
case 803...804:
return "cloud.fill"
default:
return "questionmark"
}
}
}
Syntax of a Computed Property[Bearbeiten]
- Has to be a var
var propertyName: PropertyType {
// Code
return resultOfCode
}
// i.e.
var temperatureStr: String{
return String(format: "%.1f", temperature)
}