簡體   English   中英

無法分配給受限於類的協議中的屬性-Swift編譯器錯誤

[英]Cannot assign to property in protocol constrained to class - Swift compiler error

我使用Xcode 7 beta 6,並且我有這樣的代碼:

public protocol ViewForViewModel {
    typealias ViewModelType
    var viewModel: ViewModelType! { get set }
    func bindToViewModel()
}

func afterViewInstantiated <V : ViewForViewModel where V: UIViewController, V.ViewModelType: AnyObject>(view : V, viewModel: V.ViewModelType) -> V {
    //Cannot assign to property: 'view' is a 'let' constant
    view.viewModel = viewModel // error here

    VMTracker.append(viewModel, view: view)

    return view
}

編譯器抱怨分配view.viewModel = viewModel 我了解哪些ViewForViewModel協議本身並不受限於類,但V類型僅限於UIViewController類。 它是錯誤還是功能?

UPD:它甚至抱怨UITableViewCell變量:

func registerBinding<V: BindableCellView where V: UITableViewCell>(viewType: V.Type) {
    let typeName = nameOfType(V.ViewModelType.self)

    bindings[typeName] = { [unowned self] viewModel, indexPath in
        let view = self.tableView.dequeueReusableCellWithIdentifier(V.CellIdentifier, forIndexPath: indexPath) as! V

        //Cannot assign to 'viewModel' because 'view' is a 'let' constant
        //However view is UITableViewCell that support ViewForViewModel protocol
        view.viewModel = viewModel as! V.ViewModelType

        self.onWillBind?(view, indexPath)
        view.bindToViewModel()
        self.onDidBind?(view, indexPath)

        return view
    }
}

如果編譯器無法推斷出該參數將始終是引用類型,則可以始終將class添加到協議聲明中:

public protocol ViewForViewModel: class {
  typealias ViewModelType
  var viewModel: ViewModelType! { get set }
  func bindToViewModel()
}

這樣標記了協議后,即使對象存儲在常量中,您也應該能夠為屬性分配值。

在第一種情況下,應將其視為“未實現的功能”(編譯器無法在此上下文中推斷類的行為)。 因此,要解決此問題,您必須將value設為var

func afterViewInstantiated <V : ViewForViewModel where V: UIViewController, V.ViewModelType: AnyObject>(var view : V, viewModel: V.ViewModelType) -> V

在第二種情況下,您應該提供有關錯誤(消息)和類型的更多信息。 V來自哪里?

如果編譯器抱怨協議不能用作非泛型類型,請刪除協議中的類型typealias

順便說一句,用例是什么?

暫無
暫無

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

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