Swift,来自类的多重继承

时间:2014-10-30 23:01:22

标签: ios inheritance swift compiler-errors

这是我创建的自定义类:

import UIKit
import CoreBluetooth

protocol vaBeanDelegate
{

}

class vaBean: CBCentralManager, CBCentralManagerDelegate {

override init!(delegate: CBCentralManagerDelegate!, queue: dispatch_queue_t!) {
    println("bean initialised")
    super.init()
    self.delegate = delegate
}

func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {
    println("discovered peripheral(s)")
}

func centralManagerDidUpdateState(central: CBCentralManager!) {
    switch (central.state) {
    case .PoweredOff:
        println("hardware is powered off")

    case .PoweredOn:
        println("hardware is powered on and ready")
        //centralManager.scanForPeripheralsWithServices(nil, options: nil)
    case .Resetting:
        println("hardware is resetting")

    case .Unauthorized:
        println("state is unauthorized")

    case .Unknown:
        println("state is unknown");

    case .Unsupported:
        println("hardware is unsupported on this platform");

    }
}

func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
    println("didConnectPeripheral")
}
}

我只是不知道如何从我的主ViewController初始化它。当我尝试以下操作时,它会抱怨ViewController不符合CBCentralManagerDelegate:

import UIKit

class ViewController: UIViewController {

var myBean: vaBean!

override func viewDidLoad() {
    super.viewDidLoad()
    println("blueToothTest v1.00")
    println("opening bluetooth connection ...")
    myBean = vaBean(delegate: self, queue: nil)
}

override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()}
}

4 个答案:

答案 0 :(得分:14)

Swift和Objective-C只是单一继承,一个类不能有多个超类。

当您在声明中看到Swift代码看起来像多个超类时,您会看到最多声明中的一个名称是超类,其他名称是协议名称。

在Objective-C中,这些内容将使用<angled brackets>编写,但Swift不是这样。

答案 1 :(得分:1)

Swift不支持多重继承。但是,如果你只是想访问,你的ViewController不需要继承vaBeanDelegate,正如你的问题所示。

答案 2 :(得分:0)

如果它抱怨ViewController不符合CBCentralManagerDelegate,则可以尝试使用以下代码。

extension viewController: CBCentralManagerDelegate {
    //implement the methods in CBCentralManagerDelegate here
}

迅速地,它仅是单继承,就像Abizern所说的那样,但是它支持实现多种协议,例如Java中的Interface。

在您的示例代码中,vaBean实现协议CBCentralManagerDelegate。

答案 3 :(得分:0)

您的ViewController不符合 CBCentralManagerDelegate

协议

看这个:

myBean = vaBean(delegate: self, queue: nil)

构造函数 init 的第一个参数期望参数 delegate 的对象符合协议 CBCentralManagerDelegate 。您在其中传递 self ,这是您的视图控制器,它不会实现该委托(即使它尚未定义任何函数。这也会引发错误。)

您有2种选择来解决此问题:

1)通过以下方式直接在视图控制器中实现 CBCentralManagerDelegate

class ViewController: UIViewController, CBCentralManagerDelegate { 
    // Here goes the rest of your class
    // Don't forget to add delegate functions once you added some
}

2)在文件末尾的类中添加扩展名,以增加协议的一致性

extension UIViewController: CBCentralManagerDelegate { 
    // Empty for now since the protocol does not require anything at the moment
    // Don't forget to add delegate functions once you added some
}