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.swift234 chars10 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.
gistlibby LogSnag