12

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

Daniel Shin
  • 4,956
  • 2
  • 27
  • 51
  • In which version of Xcode you are trying that code ? – Midhun MP Mar 23 '15 at 09:15
  • https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html#//apple_ref/doc/uid/TP40014097-CH15-ID241? – Larme Mar 23 '15 at 09:17

3 Answers3

23

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).

Martin R
  • 510,973
  • 84
  • 1,183
  • 1,314
3

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.

Antonio
  • 70,043
  • 10
  • 143
  • 164
0

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:).

Pierre Thibault
  • 1,705
  • 2
  • 17
  • 19