Initialization syntax

Explain the purpose of the self initialization syntax such as

init(distance: Double) {
self.distance = distance
}

In swiftui when I initialize distance I normally just say

init () {
var distance = 5
}

It seems like the first example doesn’t do anything useful

@galensmith Thanks very much for your question!

In the line:

self.distance = distance

self.distance

is referring a declared property that is contained within that class, while

= distance is referring to the property being passed in at the time of instantiation.

init(distance: Double) {
self.distance = distance
}

The self identifier indicates a reference to the class where it is being used. So if this code is declared inside a class called, “MyViewController”, then

self is a reference to MyViewController.

SwiftUI is a different beast, and so many things done in UIKit are simplified in SwiftUI, which means shorter syntax :slight_smile:

I hope this helps!

All the best.

This topic was automatically closed after 166 days. New replies are no longer allowed.