How do I make class methods / properties in Swift?

They are called type properties and type methods and you use the class or static keywords.

class Foo {
    var name: String?           // instance property
    static var all = [Foo]()    // static type property
    class var comp: Int {       // computed type property
        return 42
    }

    class func alert() {        // type method
        print("There are \(all.count) foos")
    }
}

Foo.alert()       // There are 0 foos
let f = Foo()
Foo.all.append(f)
Foo.alert()       // There are 1 foos

They are called type properties and type methods in Swift and you use the class keyword.
Declaring a class method or Type method in swift :

class SomeClass 
{
     class func someTypeMethod() 
     {
          // type method implementation goes here
     }
}

Accessing that method :

SomeClass.someTypeMethod()

or you can refer Methods in swift


Prepend the declaration with class if it's a class, or with static if it's a structure.

class MyClass : {

    class func aClassMethod() { ... }
    func anInstanceMethod()  { ... }
}

Tags:

Swift