在不同的swift文件中覆盖超类的默认初始值设定项

时间:2014-11-04 04:51:56

标签: ios macos cocoa swift

我在Vehicle.swift中编写了类Vehicle,并在Bicycle.swift中的另一个类Bicycle中继承了它。但Xcode 6.1报告了编译错误:初始化程序不会覆盖其超类中的指定初始化程序。 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
    }
}

这些代码来自Apple iOS Developer Library。链接:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_324

当在同一个.swift文件中时,它们可以通过编译。只能在不同的文件中工作。这是一个快速的错误吗?

2 个答案:

答案 0 :(得分:1)

看起来,Default Initializer从其他文件中是不可见的,就好像它被声明为private init() {}一样。 我没有找到任何有关此行为的官方文件。我认为这是一个错误。

无论如何,明确的init()声明解决了这个问题。

public class Vehicle {

    init() {} // <- HERE

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

或者@rdelmar在评论中说,numberOfWheels的显式初始值也有效:

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

答案 1 :(得分:0)

自行车不是公共类。 Apple的图书馆代码:

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