HeM*_*Met 0 compiler-errors ios swift2
我使用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
}
Run Code Online (Sandbox Code Playgroud)
编译器在转让时抱怨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
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
如果编译器无法推断,该参数将始终是引用类型,则可以始终添加class到协议声明:
public protocol ViewForViewModel: class {
typealias ViewModelType
var viewModel: ViewModelType! { get set }
func bindToViewModel()
}
Run Code Online (Sandbox Code Playgroud)
一旦协议被标记为这样,即使对象存储在常量中,您也应该能够为属性赋值.
| 归档时间: |
|
| 查看次数: |
1117 次 |
| 最近记录: |