/// Generating A Random String
func random(_ n: Int) -> String
{
let a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
var s = ""
for _ in 0..<n
{
let r = Int(arc4random_uniform(UInt32(a.characters.count)))
s += String(a[a.index(a.startIndex, offsetBy: r)])
}
return s
}
print(random(8))
// Output: 6FvUpkzp
/// Picking a Random Element from an Array
let names = ["Arthur", "Ford", "Zaphod", "Marvin", "Trillian"]
let random = names[Int(arc4random_uniform(UInt32(names.count)))]
print(random)
// Output: Marvin
extension Array
{
func random() -> Element
{
return self[Int(arc4random_uniform(UInt32(self.count)))]
}
}
/// A Convenience Function for Random Numbers
func random(_ n:Int) -> Int
{
return Int(arc4random_uniform(UInt32(n)))
}
// This will output a 100 random numbers between 0 and 99.
func random(_ range:Range<Int>) -> Int
{
return range.lowerBound + Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound)))
}
// Instead of a single input number, this function takes in a Range like 0..<42 and returns a number between 0 and 42, not including 42.