gpt4 book ai didi

ios - 无法分配给受限于类的协议(protocol)中的属性 - Swift 编译器错误

转载 作者:行者123 更新时间:2023-11-28 18:09:29 25 4
gpt4 key购买 nike

我使用 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 协议(protocol)本身并不受限于类,但 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 添加到协议(protocol)声明中:

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

一旦协议(protocol)被标记为那样,即使对象存储在常量中,您也应该能够为属性赋值。

关于ios - 无法分配给受限于类的协议(protocol)中的属性 - Swift 编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32284933/

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