Swift Class Methods

Swift Class Methods

Use static or class to define type methods that belong to the type itself rather than an instance.


Type Methods

Use class for overridable type methods; static methods cannot be overridden.

Example

class Math {
  class func square(_ n: Int) -> Int { n * n } // overridable in subclasses
  static func cube(_ n: Int) -> Int { n * n * n } // not overridable
}

print(Math.square(4))
print(Math.cube(3))


Override class func

Use class for overridable type methods; static methods cannot be overridden.

Example

class Base {
  class func greet() { print("Base") }
  static func ping() { print("Base ping") }
}

class Sub: Base {
  override class func greet() { print("Sub") }
  // static func cannot be overridden
}

Base.greet()
Sub.greet()
Base.ping()

Comments

Leave a Reply

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