Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Understand Static Functions & Properties in Swift
Written by Team Kodeco

Static functions and properties are class-level members that belong to the type itself, rather than an instance of the type. This means that they can be called without having to create an instance of the class or struct. In Swift, the keyword static is used to define a static function or property.

Static functions are useful for sharing functionality across all instances of a type. For example, you could create a static function in a math class that calculates the square of a number. This function can be called on the type itself, rather than having to create an instance of the math class.

Here’s an example code that demonstrates a static function in Swift:

struct Math {
  static func square(number: Int) -> Int {
    return number * number
  }
}

let result = Math.square(number: 4)
print(result) // 16

Static properties are used to store class-level data that is shared across all instances of a type. For example, you could create a static property in a class to store the number of instances created. This property can be accessed by any instance of the class or by the class itself.

Here’s an example code that demonstrates a static property in Swift:

class Counter {
  static var count = 0

  init() {
    Counter.count += 1
  }
}

let c1 = Counter()
let c2 = Counter()
print(Counter.count) // 2

Static functions and properties are powerful tools in Swift for sharing functionality and data across all instances of a type. They can be used to create reusable code and store class-level data that is shared across all instances of a type.

© 2024 Kodeco Inc.