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.
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