簡體   English   中英

使用Swift協議繼承

[英]Using Swift Protocol Inheritance

我正在嘗試創建一個使用傳統多態性來補償設備(例如藍牙LE,藍牙等)的委托,並且似乎無法正確地進行語法轉換。

這是我的父協議和類:

@objc protocol DeviceDelegate
{
    func didConnectToDevice(name:String)
    func didFailToConnectToDevice(name:String)
    func didDisconnectFromDevice(name:String)

    func didWriteData(data:NSData)
    func didReceiveData(data:NSData)
}

class Device: NSObject
{
    var delegate: DeviceDelegate?
}

現在,這里是子類和協議的簡化版本:

protocol BluetoothDelegate : DeviceDelegate
{
    func didFindService(name:String)
    func didFindCharacteristic(name:String)
}

class BLE: Device
{
    func someFunc()
    {
        let bluetoothDelegate = (delegate as? BluetoothDelegate)
        bluetoothDelegate.didFindService(UUIDString)
    }
}

它在該函數的第一行上引發以下錯誤:

Cannot downcast from 'DeviceDelegate?' to non-@objc protocol type 'BluetoothDelegate'

這對我來說沒有任何意義,因為它應該允許像平常的對象一樣將對象投射到孩子身上。

如果將@objc放在BluetoothDelegate前面,則會出現以下錯誤:

@objc protocol 'BluetoothDelegate' cannot refine non-@objc protocol 'DeviceDelegate'

有人對此有任何想法嗎?

當我復制代碼並將其直接粘貼到操場上,並在BluetoothDelegate定義前面添加@objc時,在以下行上會收到一條消息:

bluetoothDelegate.didFindService("asdf")

“BluetoothDelegate? 沒有名為“ didFindService”的成員

因為你曾經用過as? ,有可能bluetoothDelegatenil 您應該在此處使用可選鏈接。 替換為以下行后,操場上不會出現任何錯誤,表明您可能在代碼中做了其他未向我們展示的事情。

bluetoothDelegate?.didFindService("asdf")

或者,您可以使用以下方法:

if let bluetoothDelegate = delegate as? BluetoothDelegate {
  bluetoothDelegate.didFindService(UUIDString)
}

您看到的關於DeviceDelegate不是objc協議的消息向我表明您已將它們寫入兩個不同的文件中,並且可能不正確地向前聲明了DeviceDelegate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM