Reputation: 3977
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?
Upvotes: 1
Views: 1220
Reputation: 107131
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)
}
}
Upvotes: 1
Reputation: 2926
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).
Upvotes: 2