在iOS游戏开发中以Swift(Xcode)显示获胜者时出错

时间:2020-07-17 06:12:24

标签: ios swift xcode

我在游戏中设置了以下获胜条件:-

    var player1Score = ""

    var player1Name = ""

    var player2Score = ""
 
    var player2Name = ""

    if (player1Score > player2Score) {
        
        playerWinsLabel.text = "\(player1Name) YOU WIN!"
        
    }
    else if (player2Score > player1Score) {
        
        playerWinsLabel.text = "\(player2Name) YOU WIN!"
        
    }
    else {
        
        playerWinsLabel.text = "IT'S A TIE!"
        
    }

但是,只要player1Score达到100+,而player2Score <100,就会显示playerWinsLabel.text(player2 YOU WIN!)。但是,它应该显示出来(player1 YOU WIN!)。除了这种情况,它工作正常。任何人都可以让我知道我的代码出了什么问题。谢谢!

2 个答案:

答案 0 :(得分:2)

您将它们作为字符串处理,而应将它们设置为整数

var player1Score = 0 
var player2Score = 0 

低于100可能意味着2 ... 9是最左边的值,在字符串比较中100+大于1。

答案 1 :(得分:1)

请勿将数字存储为String

使用>和<比较字符串时,这是词法比较(考虑如何按字母顺序排列单词列表)。

例如,“ Jane”在“ John”之前(“小于”)在“ John”之前,因为它们都以J开头,但是“ a”小于“ o”,因此您无需再查找。如果玩家1的得分为“ 100”,而玩家2的得分为“ 90”,则玩家2获胜,因为“ 1”早于(小于)“ 9”。

您应将分数属性声明为Int

var player1Score = 0
var player2Score = 0

为属性分配0(整数)会隐式地将其声明为Int