create an instance of a class with a constructor in swift

To create an instance of a class with a constructor in Swift, you need to follow these steps:

  1. Define a class with a constructor:
main.swift
class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}
145 chars
10 lines
  1. Create a new instance of the class using the constructor:
main.swift
let person = Person(name: "John", age: 30)
43 chars
2 lines

Here, we create a new instance of the Person class using the constructor that takes two parameters - name and age.

  1. Access the properties of the instance:
main.swift
print("Name: \(person.name), Age: \(person.age)")
50 chars
2 lines

This will print out:

main.swift
Name: John, Age: 30
20 chars
2 lines

Here, we access the name and age properties of the person instance using dot notation.

That's it! You have now created an instance of a class with a constructor in Swift.

gistlibby LogSnag