13

I am taking a iOS course online provided by a famous university. I don't understand why the following code use override and it is legal.

  1. According to the official definition, we use override to override superclass' methods. Where is the subclass and superclass in the following code?

  2. What's been override and by what?

public override var description: String {
    return "\(url.absoluteString) (aspect ratio = \(aspectRatio))"
}
2
  • 1
    Can you show the Class where you are writing this function? Commented Aug 26, 2016 at 17:53
  • You can "override" methods in order to provide a custom behavior.
    – l'L'l
    Commented Aug 26, 2016 at 17:53

2 Answers 2

20

Here is an example:

Your original class:

class Person {
    func walk() {
        //do something
    }
}

Your subclass:

class Runner: Person {
    override func walk() {
        //do something that is different from Person's walk
    }
}

In the Runner class, there is an override with the function walk. That is because it is a subclass of Person, and it can override Person's walk function. So If you instantiate a Runner:

var usainBolt = Runner()

And you call the walk function:

usainBolt.walk()

Then that will call the overriden function that you wrote in the Runner class. If you don't override it, it will call the walk function that you wrote in Person.

2

According to the official definition, we use override to override superclass' methods.

That's correct. The superclass in your example is the class that encloses the override of description property. This could be NSObject, some other class derived from it (directly or indirectly), or some class unrelated to NSObject that has var description: String property.

description is a property that Swift classes commonly have as a way to present themselves as a string, because description provides conformance to CustomStringConvertible protocol. This is similar to toString() method of Java, and to str() method of Python.

What's been override and by what?

The implementation of the property is what's being overridden. The class that has the implementation does the overriding.

Not the answer you're looking for? Browse other questions tagged or ask your own question.