简体   繁体   中英

Initializers construction in Swift

Studying Swift i often see following construction to make an initializer:

class customClass: NSObject {

    let what: String
    let location: GeoLocation


    init(what: String, location: GeoLocation){

        self.what = what
        self.location = location
    }

It look confusing for me, what exactly does that mean? I still not understand full meaning of this, if i am already declare properties why should i make an initialiser and that construction? (repeating variable name and type, and then - self.var = var)

Also, its perfectly available for class like UIViewController to not making initializer:

class ViewController: UIViewController {

  @IBOutlet var mapView : MKMapView!

 private  var treasures: Array<Treasure> = []
 private   var foundLocations: [GeoLocation] = []
 private var polyline: MKPolyline!

//That class work fine without convenience or designated initializer

So my question is, what exactly meaning of construction of designated initializers in swift, and initializer itself, and also i want to know is that necessary? Am i able to just declare variables at header (like i did in class ViewController: UIViewController)?

Any help, explanation would be appreciated, thanks!

The point of having an initialiser is to make sure that an object of the class is correctly set up before use.

In the first example, you are declaring two immutable properties, without giving them values. When the initialiser is called, the two iVars are given properties and the class is correctly initialised for use.

In the second example, you are creating mutable properties (since you are declaring them var) and you are also giving them default values, so even without the initialiser, all the properties are set up, except in this case, since the properties are mutable you can change them to contain more useful information later.

Furthermore, Swift is stricter than Objective-C when it comes to initialisers. Your code will not compile if you do not correctly set up objects in the initialiser. Also, your code cannot leave the initialiser's scope until all the local properties are set up. This is why , when you initialise a subclass, you don't call the superclass initialiser until all the subclass properties have been set up, unlike Objective-C where the superclass initialiser is called before setting up the local properties.

All of this comes from Swift's focus on safety and resilience.

You can use structures in place of class . If you don't want to do an initialiser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM