所以,我将我的Android应用程序移植到iOS上,并且我已经开始使用Swift(3)了。
我理解计算属性的概念,我尽可能多地尝试使用它们,但它让我想到我可能会过度使用它,这会对我的应用产生性能影响
所以我的情景: 我有一个有两个字符串的课程,其中一个是我的用户名,全局以为我的应用程序,另一个是对手的用户名。所以我的代码是这样的:
class Game {
let player: String
let opponent: String
var iAmPlayer: Bool {
return player.caseInsensitiveCompare(GlobalUsername) == .orderedSame
}
init(player: String, opponent: String) {
self.player = player
self.opponent = opponent
}
}
我经常检查我的iAmPlayer布尔值,看看用户是否开始游戏,特别是在订购游戏对象时。在java中,我只是在初始化对象时设置了一个布尔变量。我想知道,如果我只是在这里使用Stored属性而不是我正在做的事情,那会更好吗?计算属性是否已优化,或者每次尝试访问iAmPlayer var时都在进行计算?
P.S。:一旦创建了Game对象,玩家和对手就不会改变。 (因此,让)
答案 0 :(得分:2)
Usermanager.instance.username
代替GlobalUsername
代码:
class Game {
let playerName: String
let opponentName: String
var isCurrentUser: Bool
init(playerName: String, opponentName: String) {
self.playerName = playerName
self.opponentName = opponentName
self.isCurrentUser = playerName.caseInsensitiveCompare(UserManager.instance.currentUserName) == .orderedSame
}
}
// Create Game object
Game(playerName: gameData.playerName,
opponentName: gameData.opponentName)
代码:
class Game {
let playerName: String
let opponentName: String
var isCurrentUser: Bool
init(playerName: String, opponentName: String, currentUserName: String) {
self.playerName = playerName
self.opponentName = opponentName
self.isCurrentUser = playerName.caseInsensitiveCompare(currentUserName) == .orderedSame
}
}
// Create Game object
Game(playerName: gameData.playerName,
opponentName: gameData.opponentName,
currentUserName: UserManager.instance.currentUserName)
代码:
class Game {
let playerName: String
let opponentName: String
var isCurrentUser: Bool
init(playerName: String, opponentName: String, isCurrentUser: Bool) {
self.playerName = playerName
self.opponentName = opponentName
self.isCurrentUser = isCurrentUser
}
}
// Create Game object
var currentUserName = UserManager.instance.currentUserName
var isCurrentUser = dameData.playerName.caseInsensitiveCompare(currentUserName) == .orderedSame
Game(playerName: gameData.playerName,
opponentName: gameData.opponentName,
isCurrentUser: isCurrentUser)
// Create Game object
var isCurrentUser = UserManager.instance.isCurrentUser(gameData.playerName)
Game(playerName: gameData.playerName,
opponentName: gameData.opponentName,
isCurrentUser: isCurrentUser)