【发布时间】:2019-12-07 19:52:21
【问题描述】:
我的开源库中有一个协议 (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。在被调用时,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 !一定是我做错了什么,但我不知道它可能是什么!
截图以防万一!
调用协议函数
协议功能的实现
【问题讨论】:
-
实际上我很惊讶
event as? T.ReturnType表达式首先编译。 -
我知道@matt!泛型功能强大且令人敬畏!很确定我在使用它们有点不负责任,但这是另一个协议 (
Camera) 的第二次实现来使用它,另一个自一月份以来一直很好!
标签: ios swift generics protocols swift-protocols