gpt4 book ai didi

swift - swift 中的通用协议(protocol)函数和左值

转载 作者:行者123 更新时间:2023-11-30 12:36:45 25 4
gpt4 key购买 nike

当我尝试调用存储的闭包时遇到以下错误。当我尝试构建时出现此错误:

“(T) -> Void”不可转换为“@lvalue (T) -> Void”(又名“@lvalue (T) -> ()”)

public protocol DataSourceProtocol {
associatedtype DataSourceItem

func item(indexPath: IndexPath) -> DataSourceItem?
func update<T>(sender : T)
}

public class AnyDataSourceSimple<T> : DataSourceProtocol {
private var itemClosure : (IndexPath) -> T?
private var updateClosure: (T) -> Void

public init<I: DataSourceProtocol>(_ concrete: I) where I.DataSourceItem == T {
self.itemClosure = concrete.item
self.updateClosure = concrete.update
}

public func item(indexPath: IndexPath) -> T? {
return itemClosure(indexPath)
}

public func update<T>(sender: T) {
// '(T) -> Void' is not convertible to '@lvalue (T) -> Void' (aka '@lvalue (T) -> ()')
updateClosure(sender)
print("update")
}
}

这是否与协议(protocol)中的通用函数定义有关?

最佳答案

如注释中所示,泛型函数的 T 与泛型类定义中的 T 是分开的。

要使其编译,你必须这样做,不确定这是否是你的意思

import Foundation

public protocol DataSourceProtocol {
associatedtype DataSourceItem
associatedtype UpdateSender

func item(indexPath: IndexPath) -> DataSourceItem?
func update(sender : UpdateSender)
}

public class AnyDataSourceSimple<T> : DataSourceProtocol {
private var itemClosure : (IndexPath) -> T?
private var updateClosure: (T) -> Void

public init<I: DataSourceProtocol>(_ concrete: I) where I.DataSourceItem == T, I.UpdateSender == T {
self.itemClosure = concrete.item
self.updateClosure = concrete.update
}

public func item(indexPath: IndexPath) -> T? {
return itemClosure(indexPath)
}

public func update(sender: T) {
updateClosure(sender)
print("update")
}
}

关于swift - swift 中的通用协议(protocol)函数和左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42760527/

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