gpt4 book ai didi

swift - 无法转换类型 '(T) -> Void' 的值

转载 作者:行者123 更新时间:2023-11-28 08:01:07 25 4
gpt4 key购买 nike

例子:

struct Wrapper<T> {
var key: Int = 0
var listeners: [Int: (T) -> Void] = Dictionary()

mutating func add(_ handler:@escaping (T) -> Void) {
self.key += 1
self.listeners[self.key] = handler
}

func get(key: Int) -> (T) -> Void {
return self.listeners[key]!
}
}

测试协议(protocol):

protocol CommonProtocol {

}

创建测试类包装器的类

class C {
var wrapper: Wrapper = Wrapper<CommonProtocol>()

func add<T: CommonProtocol>(_ handler: @escaping (T) -> Void) {
self.wrapper.add(handler) //Cannot convert value of type '(T) -> Void' to expected argument type '(CommonProtocol) -> Void'
}
}

Image with error

我得到错误:

Cannot convert value of type '(T) -> Void' to expected argument type '(CommonProtocol) -> Void'

问题:

Why (T) -> Void can't be casted to (CommonProtocol) -> Void ? The T is explicitly declared as <T: CommonProtocol>

这是我的第一个问题,如果您有任何建议,请随时与我联系

最佳答案

你不需要制作 func add通用的。当您在 func add<T: CommonProtocol>... 中指定时您明确告诉编译器您的函数接受所有 inherit CommonProtocol 的类型但是您的 Wrapper 指定接受 CommonProtocol不是继承类型。

解决方案

任一类型删除类 C:

Class C<T: CommonProtocol> {
var wrapper: Wrapper<T>
....
}

或者如果类型 T 实际上对您来说并不重要,那么:

func add(_ handler: @escaping (CommonProtocol) -> Void)

但是第二个根本没有意义。每次使用此方法时都必须对其进行向下转换(并且向下转换非常糟糕 :D)

注意:它实际上与这个问题无关,但您的选择之一是键入删除 CommonProtocol也是。

关于swift - 无法转换类型 '(T) -> Void' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46673456/

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