12
votes

I know that static keyword is used to declare type variable/method in struct, enum etc.

But today I found it can also be used in class entity.

class foo {
  static func hi() {
    println("hi")
  }
  class func hello() {
    println("hello")
  }
}

What's static keyword's use in class entity?

Thanks!

edit: I'm referring to Swift 1.2 if that makes any difference

3
In which version of Xcode you are trying that code ?Midhun MP

3 Answers

23
votes

From the Xcode 3 beta 3 release notes:

“static” methods and properties are now allowed in classes (as an alias for “class final”).

So in Swift 1.2, hi() defined as

class foo {
  static func hi() {
    println("hi")
  }
}

is a type method (i.e. a method that is called on the type itself) which also is final (i.e. cannot be overridden in a subclass).

3
votes

In classes it's used for exactly the same purpose. However before Swift 1.2 (currently in beta) static was not available - the alternate class specifier was been made available for declaring static methods and computed properties, but not stored properties.

0
votes

In Swift 5, I use type(of: self) to access class properties dynamically:

class NetworkManager {
    private static var _maximumActiveRequests = 4
    class var maximumActiveRequests: Int {
        return _maximumActiveRequests
    }

    func printDebugData() {
        print("Maximum network requests: \(type(of: self).maximumActiveRequests).")
    }
}

class ThrottledNetworkManager: NetworkManager {
    private static var _maximumActiveRequests = 2
    override class var maximumActiveRequests: Int {
        return _maximumActiveRequests
    }
}

ThrottledNetworkManager().printDebugData()

Prints 2.

In Swift 5.1, we should be able to use Self, with a capital S, instead of type(of:).