Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default initializer of superclass in different swift files

I wrote class Vehicle in Vehicle.swift and inherited it in another class Bicycle in Bicycle.swift. But Xcode 6.1 reported an compile error: initializer does not override a designated initializer from its superclass. Vehicle.swift:

import Foundation

public class Vehicle {
    var numberOfWheels: Int?
    var description: String {
        return "\(numberOfWheels) wheel(s)"
    }
}

Bicycle.swift:

import Foundation

public class Bicycle: Vehicle {
    override init() {
        super.init()
        numberOfWheels = 2
    }
}

Those codes are from Apple iOS Developer Library. Link: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_324

When in the same .swift file, they can pass the compile. Only do not work in different files. Is this a bug of swift?

like image 552
Bing Avatar asked Dec 31 '25 09:12

Bing


1 Answers

It seems, Default Initializer is invisible from other files, as if it's declared as private init() {}. I've not found any official documents about this behavior, though. I think it's a bug.

Anyway, explicit init() declaration solves the problem.

public class Vehicle {

    init() {} // <- HERE

    var numberOfWheels: Int?
    var description: String {
        return "\(numberOfWheels) wheel(s)"
    }
}

OR as @rdelmar says in comment, explicit initial value of numberOfWheels also works:

public class Vehicle {
    var numberOfWheels: Int? = nil
    var description: String {
        return "\(numberOfWheels) wheel(s)"
    }
}
like image 130
rintaro Avatar answered Jan 03 '26 03:01

rintaro