1

brand new to Swift here coming from Objective-C, created a basic class like so:

class Person {

    var name: String
    var age: Int

    init(){

        name = “Bob”
        age = 30
    }

    func printInfo(){

        print(name)
        print(age)
    }

}

Why is it okay just to use init() here? I thought I would need to use override func init(). Also do I need to call the super or anything?

KexAri
  • 3,867
  • 6
  • 40
  • 80

2 Answers2

2

From the Apple documentation:

Swift classes do not inherit from a universal base class. Classes you define without specifying a superclass automatically become base classes for you to build upon.

So basically you're not inherting from any class and thus not overriding any init method. If you're inheriting from a class, say NSObject, then yes then you would probably want to call the super class' initialiser (as you would do in Objective-C).

Steffen D. Sommer
  • 2,896
  • 2
  • 24
  • 47
  • Is it normal practice to inherit from NSObject for a simple class like this or leave it out? In Objective-C I would be using NSObject. – KexAri Dec 16 '15 at 17:02
  • I guess the strongest argument for inheriting from `NSObject` would be Objective-C compatibility. If you're all in on Swift, then I would leave it out. Check http://stackoverflow.com/questions/24057525/swift-native-base-class-or-nsobject for more information. – Steffen D. Sommer Dec 16 '15 at 17:06
  • Ah awesome thanks. Last thing. In my code above what exactly is init() doing? It's not overriding is it? – KexAri Dec 16 '15 at 17:08
  • You're not overriding a super class' init method. You're basically creating your own initialiser where you're able to define some custom initialisation. See https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html for more information. – Steffen D. Sommer Dec 16 '15 at 17:13
1

It is because you are not inheriting from any class and Person class is the base class, means it doesn't have any super class. (Note that you can't call super.init() from the init method of Person class)

If your class is inherited from any class, you need to override the init method and need to call super.init()

Like:

class Person : NSObject
{

    var name: String
    var age: Int

    override init()
    {    
        name = "Bob"
        age = 30
    }

    func printInfo()
    {    
        print(name)
        print(age)
    }
}
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • Thanks, is it normal practice to inherit from NSObject for a simple class? I would inherit in Objective-C usually. What is the init() doing in my code above? It's not overriding is it? – KexAri Dec 16 '15 at 17:03
  • @KexAri: Not mandatory in swift. But if you are using the swift class in Objective C, it'll cause issue. If your project is purely in swift, you don't need to worry about that – Midhun MP Dec 16 '15 at 17:06