Swift - Classes

Classes


This is Part 4 of our Swift tutorial series. To create a class in swift, use class keyword. The properties and methods are declared in the same way as constant and variable.

class {
init () {

}
}

Let's create a class with functions.

class mathsClass {

func add (a:Int, b:Int) -> Int {
return a+b
}
}

let mathsObject = mathsClass()

print (mathsObject.add(a:1, b:1)) // 2

Swift classes supports inheritance. We can create a parent class and inherit its properties in the child class.

class Student {
func studentName () -> String {
return "Alice"
}
}

class ReportCard : Student {

}

let studentCard = ReportCard()

print (studentCard.studentName()) // Alice

The above example had the student name in function. Let's create a property and store the value.

class Student {
var name : String

init (studentName : String) {
name = studentName
}
}

let student = Student(studentName : "Alice")

print (student.name) // Alice

Extensions

We can write custom methods for the existing classes available in swift. And it is easy and straightforward.

To create an extension, use the keyword, extension.

extension Int {
func add(a:Int)-> Int {
return self+a
}
}

let sum = 10.add(5)

print (sum) // 15



Singleton

Objective-C supports a feature to create a singleton object. The benefit of singleton object is that it can be used across the project globally without initialising multiple copies of the object. Instead the same object is referred across all classes.

to create a singleton object,

class sharedClass {
static let sharedInstance = sharedClass()

init () {
print ("Class is initialised")
}

func sayHello () {
print ("Hello")
}

}

sharedClass.sharedInstance().sayHello() // Class is initialised     
// Hello

sharedClass.sharedInstance().sayHello() // Hello

The first time the class is initialised but the consecutive times, the init method will not be called.

Comments

Popular posts from this blog

Swift - Strings

What's new in Swift 4!