[英]Optional cast to protocol's associated type is failing (returning nil)
我的開源庫中有一個協議( 鏈接以防代碼示例不夠)。
所述協議有兩種關聯類型,一種用於函數“發送”類型,一種用於“返回類型”,定義如下:
/// A protocol which can be adopted to define a function that can be performed on any given camera
public protocol CameraFunction {
/// An associated type which is taken as an input when calling this function on a `Camera` instance
associatedtype SendType
/// An associated type which is returned from the camera when calling this function on the `Camera`
associatedtype ReturnType
/// The enum representation of this given function
var function: _CameraFunction { get }
}
在函數實現中(在另一個協議上聲明的performFunction
):
func performFunction<T>(_ function: T, payload: T.SendType?, callback: @escaping ((Error?, T.ReturnType?) -> Void)) where T : CameraFunction {
switch function.function {
case .getEvent:
let packet = Packet.commandRequestPacket(code: .getAllDevicePropData, arguments: [0], transactionId: ptpIPClient?.getNextTransactionId() ?? 0)
ptpIPClient?.awaitDataFor(transactionId: packet.transactionId, callback: { (dataResult) in
switch dataResult {
case .success(let data):
guard let numberOfProperties = data.data[qWord: 0] else { return }
var offset: UInt = UInt(MemoryLayout<QWord>.size)
var properties: [PTPDeviceProperty] = []
for _ in 0..<numberOfProperties {
guard let property = data.data.getDeviceProperty(at: offset) else { break }
properties.append(property)
offset += property.length
}
let event = CameraEvent(sonyDeviceProperties: properties)
callback(nil, event as? T.ReturnType)
case .failure(let error):
callback(error, nil)
}
})
ptpIPClient?.sendCommandRequestPacket(packet, callback: nil)
我創建了一個CameraEvent
對象並嘗試向下轉換(不確定這是否是正確的術語)到T.ReturnType
。 在調用時, event
non-nil
,但是將其轉換為T.ReturnType
會給出nil
結果,即使它應該匹配!
Event.get
(.getEvent) 定義如下:
/// Functions for interacting with the event API on the camera
public struct Event: CameraFunction {
public var function: _CameraFunction
public typealias SendType = Bool
public typealias ReturnType = CameraEvent
/// Gets the current event
public static let get = Event(function: .getEvent)
}
同樣重要的是要注意,我談到的第二個協議的另一個實現(定義performFunction
函數的那個)成功地執行了非常相似的邏輯,我沒有得到 nil ! 一定是我在這里做錯了什么,但我不知道它可能是什么!
截圖以防萬一!
這是...只是調試器是一堆垃圾! 決定添加一個print
語句以確保它是nil
。 事實證明並非如此! 打印正常,但lldb
似乎認為無論出於何種原因都為零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.