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

标签 swift closures protocols

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

“(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/

相关文章:

ios - 适当的 UI 元素隐藏

javascript - 使用 ES6 模块而不是揭示模块模式的额外优势是什么?

regex - Groovy正则表达式闭包

c# - 指针类型数组上的 foreach 的闭包语义

sockets - 是否有任何关于监听 TCP 套接字的积压行为的 RFC 文档?

ios - 第一次每次快速解析时对象 id nil

swift - 访问类中的结构变量

ios - 这个键盘不会离开

http - 浏览器和 Web 服务器之间的通信是如何进行的?

objective-c - Objective - C,使用 NSDecimalNumberHandler 和 NSDecimalNumberBehaviors 协议(protocol)