2

I have an array with a few values that I'd like to select a value from randomly but I'm having some trouble with the execution. I'm new to Swift so I'm not sure what I'm doing wrong here.

let types = ["value1", "value2", "value3"]

class someClass {
    let type = String(arc4random_uniform(UInt32(types)))
}

With this code, I get the error Playground execution failed: <EXPR>:39:16: error: cannot invoke 'init' with an argument of type 'UInt32' let type = String(arc4random_uniform(UInt32(types))) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I tried something a little different to see if I could workaround this error.

let types = ["value1", "value2", "value3"]

class someClass {
    let x = arc4random_uniform(UInt32(4))
    let type = types[x]
}

But then I get this error: Playground execution failed: <EXPR>:39:22: error: 'BlogPost.Type' does not have a member named 'x' let type = types[x] ^

I've only been working with Swift for a month so far so I'd definitely appreciate it if you guys could share your insight on both of the methods I tried, and if both methods are correctable how would you rework the code for both examples to make it work?

1 Answer 1

5

Here is how you can do it:

let types = ["value1", "value2", "value3"]
let type = types[Int(arc4random_uniform(UInt32(types.count)))]
println(type)
  • The cast of count to UInt32 is necessary because arc4random_uniform takes an unsigned value
  • The cast of arc4random_uniform back to Int is required because array subscript operator [] takes an Int.

Demo (click [Compile] at the bottom to run).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.