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
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With