Created
November 19, 2016 21:05
-
-
Save AppleBetas/1ffc212c9b860b5a79133884d245ac75 to your computer and use it in GitHub Desktop.
Randoms.swift - Random helper methods for Int, Double, Float, Dictionaries, and Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Randoms.swift | |
// | |
// Created by AppleBetas on 2016-02-21. | |
// Copyright © 2016 AppleBetas. All rights reserved. | |
// | |
import Foundation | |
extension Array { | |
func randomItem() -> Element { | |
let index = Int.random(min: 0, max: self.count - 1) | |
return self[index] | |
} | |
} | |
extension Int { | |
// Returns a random Int point number between 0 and Int.max. | |
public static var random: Int { | |
get { | |
return Int.random(n: Int.max) | |
} | |
} | |
/** | |
Random integer between 0 and n-1. | |
- parameter n: Int | |
- returns: Int | |
*/ | |
public static func random(n: Int) -> Int { | |
return Int(arc4random_uniform(UInt32(n))) | |
} | |
/** | |
Random integer between min and max | |
- parameter min: Int | |
- parameter max: Int | |
- returns: Int | |
*/ | |
public static func random(min: Int = 0, max: Int) -> Int { | |
return Int.random(n: max - min + 1) + min | |
} | |
} | |
extension Double { | |
// Returns a random floating point number between 0.0 and 1.0, inclusive. | |
public static var random: Double { | |
get { | |
return Double(arc4random()) / 0xFFFFFFFF | |
} | |
} | |
/** | |
Create a random number Double | |
- parameter min: Double | |
- parameter max: Double | |
- returns: Double | |
*/ | |
public static func random(min: Double, max: Double) -> Double { | |
return Double.random * (max - min) + min | |
} | |
} | |
extension Float { | |
// Returns a random floating point number between 0.0 and 1.0, inclusive. | |
public static var random: Float { | |
get { | |
return Float(arc4random()) / 0xFFFFFFFF | |
} | |
} | |
/** | |
Create a random num Float | |
- parameter min: Float | |
- parameter max: Float | |
- returns: Float | |
*/ | |
public static func random(min: Float, max: Float) -> Float { | |
return Float.random * (max - min) + min | |
} | |
} | |
extension Dictionary { | |
mutating func merge<K, V>(dict: [K: V]){ | |
for (k, v) in dict { | |
self.updateValue(v as! Value, forKey: k as! Key) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment