Reputation: 95
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
Upvotes: 7
Views: 5971
Reputation: 131
Ternaries are nice but that may not always be what you want to use. You can declare a let without a value, and assign it within an if/else block.
let loc1Value: Double
let loc2Value: Double
if Int.random(in: 0...1) == 0 {
loc1Value = 0.5
loc2Value = 0.0
} else {
loc1Value = 0.0
loc2Value = 0.0
}
Upvotes: 3
Reputation: 547
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
}
Upvotes: 6
Reputation: 236315
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
Upvotes: 1