Reputation: 363
I am trying to pick and run a random function in swift.
Currently I have implemented a switch case like this
switch Int.random(in: 1...2) {
case 1: functionOne()
case 2: functionTwo()
default: print("error")
}
if there are more options the code gets really excessive.
How can I improve the code to make it save the extra lines? The optimum would be:
[functionOne(), functionTwo()].randomElement()
This does not work but just runs the last element in the array. Is there a way to put functions in an array and let them run?
Upvotes: 0
Views: 99
Reputation: 131471
If you want the probability of the different functions to be different then your switch statement would be a good choice:
switch Int.random(in: 1...100) {
case 1...10: functionOne() //10% of calls
case 11...100: functionTwo() //90% of calls
default: noFunction()
}
If you want them all to be equally as likely then Matt's approach seems cleaner:
let functions = [functionOne, functionTwo]
(functions.randomElement()!)()
Upvotes: 1