gpt4 book ai didi

Swift:带有回调的泛型

转载 作者:可可西里 更新时间:2023-11-01 01:37:32 24 4
gpt4 key购买 nike

我试图保留一个回调字典,其中回调可以包含一个基类类型的参数,然后我可以用任何派生类型调用回调。当我尝试这样做时,出现编译错误。我来自 C++/C# 背景,所以我很难理解这是如何在 Swift 中完成的。

这是一个简化的用例:

public func RegisterMessage<T: Message>(type: MessageType, callback: (msg: T) -> ())
{
// ERROR: Cannot assign a value of type '(msg: T) -> ()' to a value
// of type '((msg: Message) -> ())?'
MessageCallbacks[type] = callback
}

private var MessageCallbacks : [MessageType : (msg: Message) -> ()] = [:]

如果它正在编译,这里是我期望使用它的代码:

RegisterMessage<SetPositionMessage>(MessageType.SetPosition, OnSetPosition)

// This would take msg's type, using it to find the callback in the
// dictionary, and then it would pass the msg into the callback function.
let msg = SetPositionMessage()
SendMessage(msg)

public func SendMessage(msg: Message)
{
MessageCallbacks[msg.MessageType]?.(msg)
}

我想要完成的是,我有一种方法可以指定一个回调函数,该回调函数应根据发送的消息类型进行调用。

这是显示我的问题的另一个代码示例。我可以拥有一个接受派生类型的基类型容器,但这不适用于具有基类型的回调容器。

public class BaseClass {
}

public class DerivedClass : BaseClass {
}

var Container: [BaseClass] = []
Container.append(BaseClass())
Container.append(DerivedClass())

var Callbacks: [(msg: BaseClass) -> ()] = []

func BaseCallback(msg: BaseClass) {}

func DerivedCallback(msg: DerivedClass) {}

Callbacks.append(BaseCallback)
Callbacks.append(DerivedCallback)
// ERROR! Cannot assign a value of type '(DerivedClass) -> ()' to expected argument type '(msg: BaseClass) -> ()'

最佳答案

你可以使用:

MessageCallbacks[type] = (callback as! (msg: Message) -> ())

关于Swift:带有回调的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34891908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com