2015-02-23 191 views
1

我想創建一個使用傳統多態性來代替藍牙LE,藍牙等設備的代理,並且似乎無法獲得鑄造的語法權限。使用Swift協議繼承

這裏是我的父母協議和類:

@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 [email protected] protocol type 'BluetoothDelegate' 

這對我來說沒有意義,因爲它應該允許鑄造成ac像通常的對象一樣。

如果我在BluetoothDelegate我碰到下面的錯誤面前放@objc:

@objc protocol 'BluetoothDelegate' cannot refine [email protected] protocol 'DeviceDelegate' 

任何人對此有什麼想法?

回答

1

當我複製你的代碼,並將其直接粘貼到操場,並在您BluetoothDelegate定義的前面加上@objc,我得到一個消息,在這條線:

bluetoothDelegate.didFindService("asdf") 

'BluetoothDelegate?' does not have a member named 'didFindService'

因爲你已經使用as?,有一個機會,bluetoothDelegatenil。你應該在這裏使用可選的鏈接。使用以下行報告替換操場中沒有任何錯誤,表明您可能在代碼中執行了其他您未顯示的其他內容。

bluetoothDelegate?.didFindService("asdf") 

或者,你可以這樣做:

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

你看到有關DeviceDelegate不是一個objc協議的消息表示,我認爲你已經在兩個不同的文件寫的這些和可能會錯誤地宣佈DeviceDelegate

+0

我使用你的替代代碼,仍然得到相同的結果,但: 他們在兩個單獨的文件,因爲它們分別由父類和子類使用。我認爲這可能是一個編譯器錯誤,如果我將兩個協議移動到一個文件,然後編譯正確。 放在一邊,並在新發布的XCode 6.3 Beta 2中測試,它在2個獨立的文件中正常工作。 謝謝! – Khirok 2015-02-23 18:30:50