stumped
stumped

Reputation: 3293

Why do I have to override my init in Swift now?

import Foundation

class Student: NSObject
{
    var name: String
    var year: Int
    var major: String
    var gpa : String

    init(name:String, year:Int, major:String, gpa:String)
    {
        self.name = name
        self.year = year
        self.major = major
        self.gpa = gpa
    }

    convenience init()
    {
        //calls longer init method written above
    }
}

--

The error shows itself atthe line of the convenience init

Overriding declaration requires an 'override' keyword

I've tried Googling this and reading guides on initializers in Swift, but it seems like they were able to make their initializers just fine without overriding anything.

Upvotes: 6

Views: 3065

Answers (2)

jtbandes
jtbandes

Reputation: 118691

init is a designated initializer for NSObject. If you override it, you must mark this as override and call a superclass designated initializer. This follows the normal rules for initializer inheritance.

Upvotes: 7

Guillermo Alvarez
Guillermo Alvarez

Reputation: 1775

it looks like your convenience initializer is empty which is why you get the error. For example if you change it to:

convenience init() {
    self.init(name: "", year: 0, major: "nothing", gpa: "4.0")
}

the error would go away.

I wonder why you set up Student to inherit from NSObject. It doesn't look necessary for your class.

Upvotes: -1

Related Questions