Intermediate Swift 3 - Part 7: Initializers | Ray Wenderlich

In this Intermediate Swift 3 video tutorial you'll learn the basics of creating your objects through the use of initializers.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3536-intermediate-swift-3/lessons/7

Challenge file and solution file are the same thing. This happens frequently w/ the provided files.

Thanks for the heads up, DCDude! I’ve updated the materials. We’ve recently started using tech editors for our videos to catch these kinds of issues.

this video stop every few seconds… cannot be resumed if not trying to play from another point.

1 Like

Can you fix the issue of this video stopping every few seconds?

Hi Brian, Quick question - You mentioned - In Swift, we initialize all of our class variables first & then call super (parent class) designated initializer at last (instead of first as compared to other object oriented languages). I am having little difficulty understanding this concept. Can you shed some light on this with the help of an example ?

Initialization is one of the more trickier bits about Swift, especially if you are coming from something like Java or C#. In other languages, you think more along the lines of top-to-bottom. Meaning, you first construct all your parent objects before creating the child objects.

In Swift, safety comes first. The idea is that once you have all your properties set, you won’t be in a situation where they may be used (during initialization) when they aren’t ready to be used.

Take this example. Lets create a class called Person

class Person {
  var name: String

  init() {
    self.name = "Bill"
    print(speak())
  }

  func speak() -> String {
    return "Hi, my name is \(name)"
  }
}

As you can see, this simple class sets a property, then calls the speak method in the initializer. Notice that speak() actually references a property.

Now, lets examine a subclass:

class Student: Person {
  var major: String

  override init() {
    self.major = "Computer Science"
    super.init()
  }

  override func speak() -> String {
    return "Hi, my name is \(name) and I study \(major)"
  }
}

All we’re doing is adding another property but we’ve also overridden speak(). Now, when we create a new Student, the overridden speak() will be called.

By first setting the major property (this is, self.major = “Computer Science”), there will be a value present when speak() is called. Here is what it will look like in action:

var student = Student()
> Hi, my name is Bill and I study Computer Science

Give that a whirl in a playground to see what I mean.

I hope that helps!

1 Like

HI Brian, I don’t understand what is a convenience init.