当我尝试调用存储的闭包时遇到以下错误。我尝试构建时遇到此错误:
'(T) - >虚空'不可转换为' @lvalue(T) - >虚空' (又名' @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")
}
}
这是否与协议中的通用函数定义有某种关系?
答案 0 :(得分:0)
与评论中一样,通用函数的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")
}
}