Create a New Class in Swift

Below are a few code examples of how to create a new class in Swift.

Empty class

class Person {

}

Class with an initializer

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

let person = Person(age: 30, name: "Sergey")

Class with a method

class Person {
    var firstName: String
    var lastName: String
    
    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
    
    func getFullName() -> String {
        return firstName + " " + lastName
    }
}

let person = Person(firstName: "Sergey", lastName: "Kargopolov")
print("Full name: " + person.getFullName())

Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!