protocol:Cannot assign to property: 'viewModel' is a 'let' constant

截屏2022-08-12 11.33.19.png

协议定义如下:

protocol BaseViewModelProtocol{
    var goBack:(() -> Void)? { get set }
}
protocol MusicDetailViewModelProtocol:BaseViewModelProtocol{

}

viewModel定义如下:

class MusicDetailViewModel:MusicDetailViewModelProtocol{
    var goBack: (() -> Void)?
}

当直接实现BaseViewModelProtocol时,并不会报这个错

解决方案:

添加@objc标识,告诉编译器实现该protocol的对象是引用类型

@objc protocol BaseViewModelProtocol{
    var goBack:(() -> Void)? { get set }
}

参考链接:
Cannot assign to property in protocol constrained to class - Swift compiler error

你可能感兴趣的:(protocol:Cannot assign to property: 'viewModel' is a 'let' constant)