First, to create an array of URL strings is pretty straightforward:
var urls = [
"http://www.url1.com",
"http://www.url2.com",
"http://www.url3.com"
]
Now, you could get a random element of this urls array with this long line of code:
let randomURL = urls[Int(arc4random_uniform(UInt32(urls.count)))]
However, another way you could do it is to add an extension to Array
that works on all arrays:
extension Array {
public var random: Element? {
let index = Int(arc4random_uniform(UInt32(self.count)))
return self.count>0 ? self[index] : nil
}
}
Now, getting a random element of the urls array is as easy as:
urls.random
This returns an Optional
(this is because if there are no elements in an array, the random property will return nil
). So in your code you'll also need to unwrap the result of the random
property:
@IBAction func Website(_ sender: Any) {
if let urlString = urls.random,
let url = URL(string: urlString) {
UIApplication.shared.openURL(url as URL)
}
}
P.S. A couple of comments on your code:
- I recommend you rename
Website
to openRandomWebsite
(remembering to change the storyboard connections too). Methods should explain what they do, and begin with a lower case letter. If you're interested, Swift general code conventions here.
- The openURL method has been deprecated in iOS 10, so I recommend you use the open(_:options:completionHandler:) method.
Your code would look like:
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
//URL opened
})