create a class with a constructor in swift

In Swift, you can create a class with a constructor (also known as an initializer) using the following syntax:

main.swift
class MyClass {
    var myProperty: String
    
    init(myParameter: String) {
        myProperty = myParameter
    }
}
121 chars
8 lines

In this example, we have created a class called MyClass with a property called myProperty. We have also defined an initializer method called init that takes a parameter called myParameter, which is used to set the value of myProperty.

To create an instance of this class and initialize it with a value, you can use the following code:

main.swift
let myObject = MyClass(myParameter: "Hello World!")
52 chars
2 lines

This creates a new instance of MyClass and initializes its myProperty property with the value "Hello World!".

gistlibby LogSnag