Override default superclass initializer in different swift files

I wrote a Vehicle class in Vehicle.swift and inherited it in another Bicycle class in Bicycle.swift. But Xcode 6.1 reported a compilation error: The initializer does not override the 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
    }
}

      

These codes are in the 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

In the same .swift file, they can commit compilation. They just don't work in different files. Is it a quick mistake?

+3


source to share


2 answers


The Default Initializer seems to be invisible from other files, as if it were declared as private init() {}

. I haven't found any official docs about this behavior. I think this is a mistake.

In any case, explicit declaration init()

solves the problem.

public class Vehicle {

    init() {} // <- HERE

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

      



OR as @rdelmar says in the comment, explicit seed numberOfWheels

also works:

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

      

+1


source


The bike is not a public class. Code from Apple library:



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

      

0


source







All Articles