C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Init: This is a special method on the class. It is called when we create a new instance by calling Box().
Self: This keyword (present in init and area) refers to the current instance of the class.
Note: We create a new class instance with width 10 and height 5. We call the area() func, which computes the result.
Swift program that uses class, init method
class Box {
var width: Int
var height: Int
init(width: Int, height: Int) {
self.width = width
self.height = height
}
func area() -> Int {
// Return width times height.
return self.width * self.height
}
}
// Create new instance of Box class.
let test = Box(width: 10, height: 5)
// Compute area for Box instance.
let area = test.area()
// Display area.
print(area)
Output
50
Here: We can create a Unit with a String, Int argument list, or use just an Int.
Note: If a class has an optional stored property, like "model," we do not need to assign it in all the init methods.
Stored PropertySwift program that uses overloaded init methods
class Unit {
var model: String?
var modelId: Int
init(model: String, modelId: Int) {
// This init requires two arguments.
self.model = model
self.modelId = modelId
}
init(modelId: Int) {
// Only one argument.
self.modelId = modelId
}
}
// Create a Unit with the 2-argument init.
let example = Unit(model: "ABC12", modelId: 12)
print(example.modelId)
// Use 1-argument init.
let example2 = Unit(modelId: 13)
print(example2.modelId)
Output
12
13
Tip: If we assign a class instance to nil, the deinit code block is executed. In this example, we create an Optional Item.
And: When the Item instance is assigned to nil, the deinit block is run. Cleanup of system resources can occur here.
Quote: Deinitializers are called automatically, just before instance deallocation takes place. You are not allowed to call a deinitializer yourself (Swift Programming Language).
Swift program that uses deinit
class Item {
init() {
print("init called")
}
deinit {
// Called whenever class stops existing.
print("deinit called")
}
}
// Create optional Item variable.
var i: Item? = Item()
// Set optional to nil to force deinit.
i = nil
Output
init called
deinit called
Note: A failable init method returns an Optional class instance. The return value may be nil.
So: We must test the return value in a let-conditional statement (or with another Optional test).
Tip: A failable init makes sense if the class cannot logically exist if an argument is invalid.
Swift program that uses failable in it
class Square {
var width: Int! // Has default value of nil.
var height: Int!
init?(width: Int, height: Int) {
// Do not allow negative width or height.
if width <= 0 {
return nil
}
if height <= 0 {
return nil
}
self.width = width
self.height = height
}
}
// The initializer succeeds.
var square = Square(width: 10, height: 20)
if let s = square {
print(s.width)
print(s.height)
}
// The failable initializer returns nil.
var squareNegative = Square(width: -1, height: -1)
if let s = squareNegative {
// Not reached.
print(s.width)
print(s.height)
}
Output
10
20
And: We must define the "description" String property. This should return a string that contains important data about the class instance.
Item: This class provides a description that includes its size Int. Print() displays the description when passed a class instance.
PrintSwift program that uses CustomStringConvertible, description
class Item: CustomStringConvertible {
var size: Int
init(size: Int) {
self.size = size
}
var description: String {
// Custom string.
return "Item: \(self.size)"
}
}
// Create new instance.
// ... Print using CustomStringConvertible description.
let item = Item(size: 10)
print(item)
// Access the description directly.
let description = item.description
print("Description = \(description)")
Output
Item: 10
Description = Item: 10