无法在协议约束到类的属性中分配 - Swift编译器错误

时间:2015-08-29 10:14:42

标签: ios compiler-errors 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
}

编译器在分配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
    }
}

3 个答案:

答案 0 :(得分:6)

如果编译器无法推断,该参数将始终是引用类型,您始终可以将class添加到协议声明中:

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

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

答案 1 :(得分:1)

在第一种情况下,它应被视为“未实现的功能”(编译器无法在此上下文中推断类的行为)。因此,要解决此问题,您必须将value设为var

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

在第二种情况下,您应该提供有关错误(消息)和类型的更多信息。 V来自哪里?

答案 2 :(得分:0)

如果编译器抱怨该协议无法用作非泛型类型,请删除协议中的typealias

BTW,这个用例是什么?