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

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.