add a property to a class in swift

To add a property to a class in Swift, you can simply declare it inside the class block using the var or let keyword followed by the property name and its data type:

main.swift
class MyClass {
    var myProperty: String
    let myConstantProperty: Int
    
    init(myProperty: String, myConstantProperty: Int) {
        self.myProperty = myProperty
        self.myConstantProperty = myConstantProperty
    }
}
234 chars
10 lines

In the example above, the MyClass has two properties, myProperty and myConstantProperty - one declared with var and the other with let. myProperty can be both read from and written to, while myConstantProperty is immutable, meaning it can only be set once during initialization.

You can assign default values to the properties when declaring them, and also provide custom initializers for the class.

related categories

gistlibby LogSnag