我需要一些关于 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 模型中存储玩家模型,因为它不需要保留对 players
和 players
仅在更新 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/