A class is a user-defined data type that includes local methods and properties. It’s a blueprint to create objects.
Classes are an important concept in object-oriented programming. A class contains both data (variables) called properties and methods (functions defined inside a class).
We use the keyword class
to define a class in Swift.
class className{
// methods, variables
}
class Person {var name:Stringvar age:Intinit(name:String, age:Int){self.name = nameself.age = age}}let person = Person(name: "john", age: 23)print("Person(name:\(person.name), age:\(person.age))")
Person
that has two members, name
and age
. We use the initializer init()
method to initialize the values of the members name
and age
.Person
class is created with name
as john
and age
as 23
..
) notation. The values of the variables of the person
object are printed.Inheritance in object-oriented programming is the ability of a class to derive or inherit methods and properties from another class. There are two types of categories of classes that involve inheritance:
In Swift, we use the colon :
to inherit a class from another class.
class ChildClass: BaseClass {
// methods, variables
}
class Vehicle {var brandName: String = "Ferrari"func honk(){print("Honking")}}class Car: Vehicle{var model: String = "Daytona"func display(){print("Car[brand=\(brandName), model=\(model)")}}let car = Car()car.display()car.honk()
Vehicle
class is defined that has the attribute brandName
and the method honk()
.Car
class is defined that inherits from Vehicle
class. It has its own attributes and methods.Car
class called car
is created.display()
method of the Car
class is invoked.honk()
method of the Vehicle
class is invoked on the car
instance as the Car
class inherits from the Vehicle
class.