【问题标题】:Cannot convert return expression of type 'Int' to return type 'Property<Int>无法将“Int”类型的返回表达式转换为“Property<Int>”类型
【发布时间】:2018-05-08 12:30:11
【问题描述】:

我正在尝试在一个测试项目中使用 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
    }
}

当我尝试return self.comment.id 时,Xcode 显示以下错误:

无法将“Int”类型的返回表达式转换为返回类型 '属性

这是有道理的 - comment.id 是 Int 而self.id 是 Observable&lt;Int&gt;。但是如何使它工作,因为我不想将Comment 类型中的属性定义为Observable。

【问题讨论】:

    标签: swift xcode mvvm


    【解决方案1】:

    已修复 - 只需更改语法:

    struct CommentViewModel {
    
        private let comment: Observable<Commentable>
    
        init(comment: Commentable) {
            self.comment = Observable(comment)
        }
    
        public var id: Observable<Int> {
            return Observable(comment.value.id)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多