Properties: a little piece of the pie
Syntax:struct MyStruct{
var propString: String
let propInt: Int
}
Properties associate values with a particular class, structure, or enumeration. While typically they are associated with instances of a particular type, properties can be of type properties. There are two main types of properties, stored and computed.
Stored properties - stores constant and variable values as part of an instance / provided only by classes and structures
Computed properties - Can be used by classes, structures, and enumerations. Computed properties don't actually store a value themselves, but provide/retrieve values for other properties via getter and (optional) setter.
/* Below is an example of a struct, SampleStructure, with 2 stored properties, color and scaleFactor. */
struct SampleStructure {
var color = "blue"
var scaleFactor = 1.0
}
/* Below is an example of a class, Meal, with 2 stored properties, the constant appetizer and the variable dinner, and 1 computed property, using the getter to return a value for tip. */
class Meal {
let appetizer = 5
var dinner = 15
var tip : Int {
get{
return (appetizer+dinner)/5
}
}
}
/* Below is an example of an enumeration, SampleEnum, with 1 "stored" property, size. Since enums are not allowed to have stored properties directly, it needs to be defined as a computed property to be accepted by the compiler. */
enum SampleEnum {
var size: Int {
get {
return 1
}
}
}