Initialization
Intro
Initialization of any type is very important and determines how the code flow is being executed with which type of data and reference strategies.
Including the default initialization for class, structs in Swift.
Class
We need to specify the initializer for class.
class Person {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let kay = Person(name: "Kautilya", age: 28)
Struct
We don't need to specify the initializer for structs.
struct Person {
let name: String
let age: Int
}
let kay = Person(name: "Kautilya", age: 28)
Static Functions
- We can directly access the static function as if it was a class method. Like
ClassSomething.doSomething()
- If we want to do something in the class before initializing other stored variables / properties we can do that using a static function. Since inherently it treats itself as its own
class doSomething()
- Static dispatch more performant
class ClassSomething {
let desc: String
init() {
let storedValue = Self.doSomething()
desc = storedValue ? "We Got Some" : "None"
}
static func doSomething() -> Bool {
return true
}
}
Singleton Pattern
Property Getter and Setters
class Temperature {
var celsius: Float = 0.0
var fahrenheit: Float {
get {
((celsius * 1.8) + 32.0)
}
set(temp) {
celsius = (temp - 32)/1.8
}
}
}
let temp = Temperature()
temp.fahrenheit = 99
print (temp.celsius)