强制转换为协议的关联类型失败(返回nil)

问题描述 投票:0回答:1

我的开源库(link in-case code samples aren't enough)中有一个协议。

所述协议具有两种关联的类型,一种用于函数“发送”类型,一种用于“返回类型”,如下所示:

/// 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。在调用点,eventnon-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函数的一种)成功地实现了非常相似的逻辑,我不会退缩!这里肯定有我做错了什么,但我不知道这可能是什么!

截屏以防万一!

调用协议的功能

Calling the protocol function

协议功能的实现

Implementation of the protocol function

ios swift generics protocols swift-protocols
1个回答
0
投票

这是...只是调试器是一堆垃圾!决定添加print语句以确保绝对是nil。事实并非如此!可以正常打印,但是lldb似乎出于任何原因都认为它为零。

© www.soinside.com 2019 - 2024. All rights reserved.