I'm trying to implement the MVVM pattern using Bond in a test project.
我正在尝试在测试项目中使用Bond实现MVVM模式。
The idea is simple:
这个想法很简单:
- Define an abstraction which the viewModel then uses.
- Make a concrete type from this abstraction.
- Inject this concrete type in the viewModel.
定义viewModel随后使用的抽象。
从这个抽象中做出具体的类型。
在viewModel中注入此具体类型。
This is my code so far:
到目前为止这是我的代码:
// 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 shows the following error when I try to return self.comment.id
:
当我尝试返回self.comment.id时,Xcode显示以下错误:
Cannot convert return expression of type 'Int' to return type 'Property
无法将“Int”类型的返回表达式转换为返回类型“Property”
This makes sense - comment.id
is an Int
and self.id
is an Observable<Int>
. How do make this work though, since I don't want to define the properties in my Comment
type as Observable
.
这是有道理的 - comment.id是一个Int,self.id是一个Observable
1 个解决方案
#1
0
Fixed it - just had to change the syntax:
修正了它 - 只需更改语法:
struct CommentViewModel {
private let comment: Observable<Commentable>
init(comment: Commentable) {
self.comment = Observable(comment)
}
public var id: Observable<Int> {
return Observable(comment.value.id)
}
}
#1
0
Fixed it - just had to change the syntax:
修正了它 - 只需更改语法:
struct CommentViewModel {
private let comment: Observable<Commentable>
init(comment: Commentable) {
self.comment = Observable(comment)
}
public var id: Observable<Int> {
return Observable(comment.value.id)
}
}