swift - 无法将“Int”类型的返回表达式转换为“Property”类型
问题描述
我正在尝试在测试项目中使用Bond来实现 MVVM 模式。
这个想法很简单:
- 定义 viewModel 然后使用的抽象。
- 从这个抽象中创建一个具体的类型。
- 在 viewModel 中注入这个具体类型。
到目前为止,这是我的代码:
// 1.
protocol Commentable {
var id: Int { get }
var name: String { get }
var body: String { get }
}
// 2.
struct Comment: Commentable {
var id: Int
var name: String
var body: String
}
// 3.
struct CommentViewModel {
private let comment: Commentable
init(comment: Commentable) {
self.comment = comment
}
public var id: Observable<Int> {
return self.comment.id
}
}
当我尝试时,Xcode 显示以下错误return self.comment.id
:
无法将“Int”类型的返回表达式转换为“Property”类型
这是有道理的 - comment.id
is an Int
and self.id
is an Observable<Int>
。但是如何使它工作,因为我不想将我的Comment
类型中的属性定义为Observable
.
解决方案
修复它 - 只需要更改语法:
struct CommentViewModel {
private let comment: Observable<Commentable>
init(comment: Commentable) {
self.comment = Observable(comment)
}
public var id: Observable<Int> {
return Observable(comment.value.id)
}
}
推荐阅读
- c - LCM,然后以矩阵形式表示
- regex - Angular 9 - Validators.pattern('^[0-9][0-9][0-9]$') 与 012 等前导 0 数字不匹配
- postgresql - SpringBoot+Kotlin+Postgres 和 JSONB:“org.hibernate.MappingException:没有 JDBC 类型的方言映射”
- sqlite - ElectronNet with .net core 3.0 Sqlite 找不到表
- javascript - 在悬停链接上将 Div 水平移动到当前悬停的链接位置
- c# - 获取指向实体框架中相同外键引用的所有实体
- list - Scala迭代列表的两个连续元素
- r - USarrests data.frame in R - 哪个州(行)呈现最小和最大的犯罪率(列)
- maven - 我添加时 Jacoco 报告生成失败
确保插件配置的属性 - javascript - 将自定义键盘设置为默认值