Can you show me when and why I should use keyword static and when I should use keyword class? (This is Type Property Syntax in Swift)
-
Compare http://stackoverflow.com/questions/29206465/static-vs-class-as-class-variable-method-swift. – Martin R Apr 23 '17 at 09:57
2 Answers
The difference between a function defined as static func
and another one defined as class func
is that static
is for functions of structures and enumerations, and class
is mainly for functions of protocols and classes.
Class functions can also be overridden by subclasses. For example:
class Animal{
class func generateAnimalSound(){
print("Some Animal Sound")
}
static func isAnimal() -> Bool{
return true
}
}
class Cat: Animal{
override class func generateAnimalSound(){
print("Meow!")
}
}
var someAnimal = Animal.generateAnimalSound() // prints "Some Animal Sound"
var cat = Cat.generateAnimalSound() // prints "Meow!"
However, if you try to override the static member function isAnimal()
, this will result in an error:
Cannot override static method
That's obviously because static methods cannot be overridden by subclasses. You should read the documentation provided both by Apple and other StackOverflow related questions:

- 4,719
- 5
- 26
- 44
You should check the Guides written by Apple on "The Swift Programming Language". The page about Classes and Structures is relevant for you. Read them and understand the examples. Then you will know when to use structs and when not.
This useful excerpt should answer your question: The Swift Programming Language - Classes and Structures
Comparing Classes and Structures
Classes and structures in Swift have many things in common. Both can:
- Define properties to store values
- Define methods to provide functionality
- Define subscripts to provide access to their values using subscript syntax
- Define initializers to set up their initial state
- Be extended to expand their functionality beyond a default implementation
- Conform to protocols to provide standard functionality of a certain kind
Classes have additional capabilities that structures do not:
- Inheritance enables one class to inherit the characteristics of another.
- Type casting enables you to check and interpret the type of a class instance at runtime.
- Deinitializers enable an instance of a class to free up any resources it has assigned.
- Reference counting allows more than one reference to a class instance.
NOTE: Structures are always copied when they are passed around in your code, and do not use reference counting.

- 706
- 4
- 25