无法将类型为'Int'的返回表达式转换为返回类型'Property

时间:2022-09-25 14:20:49

I'm trying to implement the MVVM pattern using Bond in a test project.

我正在尝试在测试项目中使用Bond实现MVVM模式。

The idea is simple:

这个想法很简单:

  1. Define an abstraction which the viewModel then uses.
  2. 定义viewModel随后使用的抽象。

  3. Make a concrete type from this abstraction.
  4. 从这个抽象中做出具体的类型。

  5. Inject this concrete type in the viewModel.
  6. 在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 。如何使这个工作,因为我不想在我的注释类型中将属性定义为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)
    }
}