为什么我不能在swift中继承多个类,就像它的库类一样

时间:2014-08-31 19:29:00

标签: swift

我尝试通过继承两个类来创建myPet,但错误例如:

import UIKit
class SecondViewController: UIViewController, UITextFieldDelegate {
    // No Error
}

然后定义了以下类,然后创建新类myPets,我喜欢继承Dog和Substance。但是错误:来自班级的多重继承' Dog'和'物质'

class Dog:Animal {
    func sound()->String {
        return "Hong Hong"
    }
}

class Substance {
    func livingCompound()->String {
        return "Consist of bio-molecule"
    }
}

class myPets:Dog, Substance {
    func itsAddress()->String {
        // Error:Multiple inheritance from classes 'Dog' and 'Substance'
    }
}

1 个答案:

答案 0 :(得分:62)

Swift不支持多重继承,遵循目标C。这不是两个类的继承:

class SecondViewController: UIViewController, UITextFieldDelegate

它是从一个类UIViewController继承并采用UITextFieldDelegate协议。阅读https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

的协议