7

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

1
  • Why use NSNumber? Use Double, or Int, or some other specific Swift type. Commented Dec 3, 2018 at 21:17

3 Answers 3

6

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's called the ternary conditional operator and is available in many languages like C, Javascript, PHP. It's not unique to Swift
3

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
}

1 Comment

This answer is less specific to the OP's problem, but feels like a better answer to the OP's general question, extending it to let constants as well as vars.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.