OneBite.Dev - Coding blog in a bite size

Declare A Class In Swift

Code snippet for how to Declare A Class In Swift with sample and detail explanation

Swift is a powerful and user-friendly programming language for iOS, macOS, watchOS, and the like. This article is aimed at helping you understand how to declare a class in Swift.

Code snippet for Declaring a Class in Swift

Here’s a simple code snippet on how to declare a class in Swift:

class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name 
        self.age = age
    }
}

Code Explanation for Declaring a Class in Swift

In the code snippet provided, we are declaring a class in Swift. Here’s a step-by-step explanation:

  1. Classes in Swift are introduced using the ‘class’ keyword. In this case, we have declared a class called ‘Person’.
class Person {
  1. Within the ‘Person’ class, we have defined two properties, ‘name’ and ‘age’, with respective data types ‘String’ and ‘Int’.
var name: String
var age: Int
  1. The ‘init’ keyword is used to define a method that gets called when an instance of the class is created. This is known as an initializer. In this case, the initializer takes in two parameters, ‘name’ and ‘age’.
init(name: String, age: Int) {
  1. Within the initializer, we have two lines of code that set the values of the ‘name’ and ‘age’ properties to the values of the input parameters. The ‘self’ keyword is used to refer to the current instance of the class.
self.name = name 
self.age = age
}
  1. Finally, we close off the class with an ending curly bracket.

This is a basic introduction on how to declare a class in Swift. Once you declare a class, you can create new instances of it, add methods to it, inherit from it, and more, thereby reaping the rich benefits of object-oriented programming.

swift