簡體   English   中英

通用協議功能和左值迅速

[英]Generic protocol functions & lvalue in swift

當我嘗試調用存儲的閉包時遇到以下錯誤。 嘗試構建時出現此錯誤:

'(T)-> Void'不能轉換為'@lvalue(T)-> Void'(aka'@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")
  }
}

這在某種程度上與協議中的泛型函數定義有關嗎?

正如評論,你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")
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM