Skip to content

Instantly share code, notes, and snippets.

@aydenp
Last active March 21, 2018 01:43
Show Gist options
  • Select an option

  • Save aydenp/140f937fdd7e9772aad7b31dafa93c64 to your computer and use it in GitHub Desktop.

Select an option

Save aydenp/140f937fdd7e9772aad7b31dafa93c64 to your computer and use it in GitHub Desktop.
Easy randoms in Swift
//
// Randoms.swift
//
// Created by Ayden Panhuyzen on 2018-03-17.
// Copyright © 2018 Ayden Panhuyzen. All rights reserved.
// https://gist.github.com/aydenp
//
import UIKit
// MARK: Integers
extension BinaryInteger {
/// Returns a random integer between min and max.
public static func random(min: Self = 0, max: Self) -> Self {
return .random(n: max - min + 1) + min
}
/// Returns a random integer between 0 and n-1.
public static func random(n: Self) -> Self {
return Self(arc4random_uniform(UInt32(n)))
}
}
extension Int {
/// Returns a random Int point number between 0 and Int.max.
public static var random: Int {
return .random(n: .max)
}
}
// MARK: Floating Point Numbers
extension FloatingPoint {
/// Returns a random floating point number between 0.0 and 1.0, inclusive.
public static var random: Self {
return Self(arc4random()) / 0xFFFFFFFF
}
/// Returns a random floating point number between min and max.
public static func random(min: Self = 0, max: Self) -> Self {
return .random * (max - min) + min
}
}
// MARK: Booleans
extension Bool {
/// Returns a random boolean.
public static var random: Bool {
return .random(probability: 1)
}
/// Returns a random boolean with the chance of being true probability:1.
public static func random(probability: Int) -> Bool {
return Int.random(n: probability + 1) <= 0
}
}
// MARK: Collections
extension RandomAccessCollection {
/// Returns a random item from the array
public var random: Element {
let offset = Int.random(min: 0, max: numericCast(count) - 1)
let idx = index(startIndex, offsetBy: numericCast(offset))
return self[idx]
}
}
// MARK: Colors
extension UIColor {
/// Returns a random solid colour.
public static var random: UIColor {
return .init(red: .random, green: .random, blue: .random, alpha: 1)
}
/// Returns a random colour with a randomized alpha.
public static var randomWithAlpha: UIColor {
return random.withAlphaComponent(.random)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment