Swift Class Properties

Swift Class Properties

Store state in class properties. Use static for type properties shared across all instances.


Stored and Computed

Use var for stored properties and let for constants.

Example

class User {
  var name: String // stored
  var greeting: String { "Hello, \(name)" } // computed
  static var appName = "MyApp" // type property
  init(name: String) { self.name = name }
}

REMOVE ADS


Property Observers

Use willSet and didSet to react to changes on stored properties.

Example

class Player {
  var score: Int = 0 {
willSet { print("About to set to \(newValue)") }
didSet { print("Changed from \(oldValue) to \(score)") }
} } let p = Player() p.score = 10

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *