Swiftly

Swift 5.7 references for busy coders

Properties

Properties are variables or constants that belong to a struct, class, or enum. Properties can belong either to an instance or a type.

Instance properties

Instance properties are variables or constants that belong to an instance of a struct, class, or enum. Example:

struct Person {
  let name: String
}

let person = Person(name: "Amy")
print("person's stored property 'name' is \(person.name)") // person's stored property 'name' is Amy

A stored property can have an initial value and change over time:

struct Person {
  var name: String = "No Name"
}

var person = Person()
print(person.name) // No Name
person.name = "Amy"
print(person.name) // Amy

If a stored property is of an optional type, the default value is nil:

struct Person {
  var name: String?
}

var person = Person()
print(person.name) // nil

Static/class properties

Static and class properties (also known as type properties) belong to a struct/class type itself, rather than an instance of a struct/class. If a type property is a stored property, it must have an initial value. They are declared with static:

struct Person {
  static let greeting = "Hello"
  let name: String

  init(name: String) {
    self.name = name
  }
}

print(Person.greeting) // Hello
class Person {
  static let greeting = "Hello"
  let name: String

  init(name: String) {
    self.name = name
  }
}

print(Person.greeting) // Hello

Computed properties

Computed properties are variables that are computed instead of holding a stored value. See Variables ยง Computed variables (get and set) for more information.

Further reading