ios - Swift View 模型 : function vs setter with side effect

标签 ios swift mvvm architecture viewmodel

我需要一些关于 View 模型架构的意见,在我的项目中我需要一个显示游戏准备状态的屏幕的 View 模型,比如我需要 3 个以上的玩家开始游戏,并且 View 模型有一个字符串属性状态,我的 View Controller 中有一组从 API 检索到的玩家。

选项 1:

// `gameStatusLabel` is a get property and only set internally when
// updating players via function
class GameStatusViewModel: NSObject {

  private(set) var gameStatusLabel: String

  func updatePlayers(players: [Player]?) {
    if let players = players, players.count > 3 {
      gameStatusLabel = "Ready to start"
    } else {
      gameStatusLabel = "Not enough player(s)"
  }
}

选项 2:

// `gameStatusLabel` is a computed property based on `players.count`

class GameStatusViewModel {

    weak var players: [Player]?

    var gameStatusLabel: String {
        if let players = self.players {
            if players.count > 3 {
                return "Ready to start"
            }
        }
        return "Not enough player(s)"
    }
}

由于我是 Swift 的新手,所以我想问一下上面哪个选项更好,为什么? (或者如果有其他更好的选择)

选项 1 不在 View 模型中存储玩家模型,因为它不需要保留对 playersplayers 仅在更新 gameStatusLabel 时需要,而 Option 2 保持对玩家的弱引用并使 gameStatusLabel 成为计算属性,这里的问题是选项 2 中的 players 只需要一个 setter,我不知道我是否可以只为没有 getter 的属性设置一个 setter(这似乎是选项 1)。

提前致谢!

最佳答案

计算属性的一个问题是您并不总是意识到它们的变化。如此多的程序员通常在大型项目中使用它们时犹豫不决,请参阅 this link了解更多信息。

关于ios - Swift View 模型 : function vs setter with side effect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47149363/

相关文章:

iOS 应用程序库目录 <uid> 总是会更改

ios - 在 Xcode 中连接到服务器时出现错误 "Timed out waiting for the socket to be ready for a write"

ios - 如何在单击按钮时打开 instagram 应用程序

ios - 从ios swift中的多个类库进行子类化

c# - ViewModel 的版本控制

ios - 返回所选项目时选项卡栏不可见

ios - 试图找出如何在 Swift 2.0 中加载多个图像序列

ios - 如何将数据从基于 plist 的 UITableView 传递到 UIViewController

ios - 具有业务和数据层的 Swift MVVM 示例

c# - 将模型与 View 模型分开有什么意义? (MVVM)