Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make class methods / properties in Swift?

Tags:

swift

Class (or static) methods in Objective-C were accomplished using + in declarations.

@interface MyClass : NSObject  + (void)aClassMethod; - (void)anInstanceMethod;  @end 

How can this be achieved in Swift?

like image 936
Erik Kerber Avatar asked Jun 06 '14 17:06

Erik Kerber


People also ask

How do you create a class method in Swift?

Type methods for 'classes' are defined by the 'func' keyword and structures and enumerations type methods are defined with the 'static' keyword before the 'func' keyword. Type methods are called and accessed by '. ' syntax where instead of calling a particular instance the whole method is invoked.

Does Swift support class methods?

In Swift, you can define type-level methods for all classes, structures, and enumerations. Each type method is explicitly scoped to the type it supports. Type methods are called with dot syntax, like instance methods.

What is class method in Swift?

A Swift function defined inside a class is called method. For example, class Person { . . . // define methods func greet() { // method body } } Here, greet() is a method defined inside the Person class. Before you learn about methods, make sure you know the working of class and struct in Swift.

What is Swift class property?

A Swift variable or constant defined inside a class or struct are called properties. For example, class Person { // define properties var name: String = "" var age: Int = 0 ... } Here, inside the Person class we have defined two properties: name - of String type with default value ""


1 Answers

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 
like image 180
Pascal Avatar answered Oct 07 '22 03:10

Pascal