Swift Introduction | Class Basics | Type Properties and Type Methods
Ordinary properties and methods require an instance. A class can also provide properties and methods that you use directly through the class. These are called type properties and type methods.
To declare type properties and type methods, add the class modifier. You can then call them directly through the class.
Keep the following points in mind when using type properties and type methods.
-
A type property can be a computed property. An ordinary stored property is not available. Because there is no class-level stored variable, a setter for a computed property also has limited use.
-
A type method can use only type methods and type properties. It cannot use ordinary properties and methods that belong to instances.
The following is an example.
class Exchange {
class var rate:Double {
return 1005.0
}
class func DollarToWon(d:Double)->Int {
return Int(d * rate)
}
class func WonToDollar(y:Int)->Double {
return Double((y * 100) / Int(rate)) / 100
}
}
print(Exchange.DollarToWon(1.5))
print(Exchange.WonToDollar(1500))
This example defines an Exchange class that converts won to dollars and dollars to won. It provides the rate type property and two type methods for the calculations. A class centered on calculations can be used efficiently through type methods because there is no need to create an instance each time.