1
class Personnage {
    var vie = arc4random_uniform(10) + 1;
    var force = arc4random_uniform(8) + 1;
    var chance = arc4random_uniform(2);
    func attaquePar(joueur1:Personnage) ->String {
        var differenceForce = self.force - joueur1.force
        var coup = differenceForce + chance
        if coup >= self.vie {
            return "tu mas eu"
        } else if coup < self.vie {
            self.vie = self.vie - coup
            return "jai rien senti macaque \(self.vie)"
        } else {
            return "heu?"
        }
}
}
let toto = Personnage()
let cafard = Personnage()
toto.attaquePar(cafard)

Hi, I am having an error message at line 6. It works some times and other it does not. Here it is : Execution was interrupted, reason EXC_BAD_INSTRUCTION (code=EXC I386_INVOP subcode=0x0). I imagine that there is an invalid operation, but i don't undestant why i get this.

Airseb
  • 13
  • 2
  • 1
    I assume this is on the line `var differenceForce = self.force - joueur1.force`? Could you check in the debugger that `self.force` and `joueur1.force` are what you expect them to be? – Jim Wright Jan 09 '18 at 14:25
  • Thanks for your time Jim. I got the answer below. – Airseb Jan 09 '18 at 19:05

2 Answers2

1

The return type from arc4random_uniform() is UInt32, and computing the difference

var differenceForce = self.force - joueur1.force

will abort with a runtime exception the second operand is greater that the first operand, i.e. the result is not representable as the (unsigned) UInt32. Unlike in some other programming langages, results are not implicitly promoted to Int or wrapped around.

A simple example:

let a = UInt32(3)
let b = UInt32(5)
let c = a - b // 

A possible solution is to convert all numbers to Int, so that differences can be computed without problems:

var vie = Int(arc4random_uniform(10)) + 1
var force = Int(arc4random_uniform(8)) + 1
// etc 
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

Thank you Martin. You were totally right.

Converting the variable type from UInt32 to Int was the solution.

var life = arc4random_uniform(10) 
var life = int(arc4random_uniform(10)) 
Airseb
  • 13
  • 2
  • 1
    You are welcome, glad to help. – Note however that the preferred way of confirming a solution is to *accept* the answer (by clicking on the check mark). See https://stackoverflow.com/help/someone-answers for more information – Martin R Jan 09 '18 at 21:43