You can use an initializer to set default property values:
struct Example {
var upvotes: Int
init() {
upvotes = 42
}
}
let myExample = Example() // call the initializer
print(myExample.upvotes) // prints: 42
Or, specify default property values as a part of the property's declaration:
struct Example {
var upvotes = 42 // the type 'Int' is inferred here
}
Classes and structs must set all stored properties to an appropriate initial value by the time an instance is created. This example will not compile, because the initializer did not give an initial value for downvotes
:
struct Example {
var upvotes: Int
var downvotes: Int
init() {
upvotes = 0
} // error: Return from initializer without initializing all stored properties
}