Initializing a Swift Object
When we create an object of a class, we can optionally pass some arguments to initialize its properties. These arguments are passed to the initializer method of the class, which sets the initial values for the properties or performs other tasks.
Syntax:
var objectName = ClassName(arguments)
For example, we can define an initializer for the Bike class that takes two arguments: name and gears. The initializer assigns these arguments to the corresponding properties of the object.
Swift
// Author: Nikunj Sonigara class Bike { // stored properties var name = "" var gears = 0 // computed property var description: String { return "This is a \(name) with \(gears) gears." } // methods func start() { print ( "The bike is starting." ) } func stop() { print ( "The bike is stopping." ) } // initializer init (name: String , gears: Int ) { self .name = name self .gears = gears } } var bike3 = Bike(name: "Splendor" , gears: 4) print (bike3.description) // This is a Splendor with 4 gears. |
Output:
This is a Splendor with 4 gears.
Class and Object in Swift
Swift is an object-oriented programming language that supports the concept of classes and objects. In this article, we will learn what are classes and objects, how to define them, and how to use them in Swift.