Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting variable values via an IF statement in Swift

Tags:

swift

I am new to Swift. I am generating a random number (0 or 1) using the following:

var locValueDeterminer = Int.random(in: 0...1)

Based on the output of this, I want to set a variable appropriately:

if locValueDeterminer = 0 {
    var loc1Value : NSNumber = 0.5
    var loc2Value : NSNumber = 1
}
else {
    var loc1Value : NSNumber = 0.0
    var loc2Value : NSNumber = 1
}

However this returns many errors. What would be the correct conditional statement to use here?

Thanks

like image 499
Steve Jobs Avatar asked Dec 03 '18 21:12

Steve Jobs


2 Answers

Instead of == you wrote = in your if statement, and by the way here's a shorter version of that code

let locValueDeterminer = Int.random(in: 0...1)
    
let loc1Value = locValueDeterminer == 0 ? 0.5 : 0.0
let loc2Value = 1.0

Asking what locValueDeterminer == 0 ? 0.5 : 0.0 means?-

it's equivalent to condition ? something : something else

So in a way it translates to:

if locValueDeterminer == 0{
   loc1Value = 0.5
}else{
   loc1Value = 0.0
}
like image 63
Niv Avatar answered Oct 13 '22 16:10

Niv


If your intend is to generate a true/false random condition in Swift 4 you can simply use Bool's random method:

let loc1Value = Bool.random() ? 0.5 : 0
like image 37
Leo Dabus Avatar answered Oct 13 '22 16:10

Leo Dabus