0

I have items in an array, and I want Xcode to randomly choose one of them to display, I am pretty new to coding so it would be great if you could explain in detail. I want it to pick the one from the array and then PrintLn. This is my current code.

   import UIKit

class Player1: UIViewController {

var stringArray = ["string1", "string2", "string3"]



override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func truth() {
     print(stringArray.random())
}




/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}
Ben77006
  • 123
  • 1
  • 1
  • 6

1 Answers1

0

You can add this little extension to Array class:

extension Array {
    public func random() -> Element {
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

And then you can use the random() function of the Array like this:

var stringArray = ["string1", "string2", "string3"]
print(stringArray.random())
bcamur
  • 894
  • 5
  • 10
  • I am getting an error on line 2, "Expected Declaration". My code is now in my question. – Ben77006 Mar 14 '16 at 22:28
  • You need to write the second line in a function – bcamur Mar 15 '16 at 06:56
  • I changed the code, (which is now above) and it is now got an error saying "Value of type '[String]' has no member 'random'" – Ben77006 Mar 16 '16 at 00:02
  • Holy moly, my bad, I forgot I had an extension for this, edited the answer. – bcamur Mar 16 '16 at 07:07
  • I'm not sure if I'm doing something very wrong, but on the extension code line. I'm getting an error saying "Declaration is only valid at file scope". I'm guessing I'm getting this error because it's in the wrong spot, where am I meant to put it. Also obviously because it is not recognising the extensions the print line is getting the same error of "Expected Declaration". Your help so far it greatly appreciated! – Ben77006 Mar 16 '16 at 22:29
  • That error means that you are putting it in the wrong scope, probably in the class code in this case. You need to put the extension code outside any curly braces, as if you were defining a new class. You can even create a new swift file called something like MyExtensions.swift, and put the extension code in it. – bcamur Mar 17 '16 at 08:00