首页 > 解决方案 > 无法将“Int”类型的返回表达式转换为“Property”类型

问题描述

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

这个想法很简单:

  1. 定义 viewModel 然后使用的抽象。
  2. 从这个抽象中创建一个具体的类型。
  3. 在 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.idis an Intand self.idis an Observable<Int>。但是如何使它工作,因为我不想将我的Comment类型中的属性定义为Observable.

标签: swiftxcodemvvm

解决方案


修复它 - 只需要更改语法:

struct CommentViewModel {

    private let comment: Observable<Commentable>

    init(comment: Commentable) {
        self.comment = Observable(comment)
    }

    public var id: Observable<Int> {
        return Observable(comment.value.id)
    }
}

推荐阅读