Skip to content

Instantly share code, notes, and snippets.

@willwfsp
Created August 19, 2020 13:55
Show Gist options
  • Save willwfsp/ab2f4b5a816c6745c513fef690f5461b to your computer and use it in GitHub Desktop.
Save willwfsp/ab2f4b5a816c6745c513fef690f5461b to your computer and use it in GitHub Desktop.
Utility to generate random values
import Foundation
public protocol Random {
static var anyValue: Self { get }
}
extension Optional: Random where Wrapped: Random{
public static var anyValue: Optional<Wrapped> {
let optional = Optional<Wrapped>(.anyValue)
return Bool.random() ? optional : nil
}
}
extension Bool: Random {
public static var anyValue: Bool {
Bool.random()
}
}
extension Double: Random {
public static var anyValue: Self {
Double.random(in: -10 ..< 10)
}
}
extension Int: Random {
public static var anyValue: Self {
Int.random(in: -100_000 ..< 100_000)
}
}
extension String: Random {
public static var anyValue: String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<20).map{ _ in letters.randomElement()! })
}
}
extension URL: Random {
public static var anyValue: URL {
URL(fileURLWithPath: .anyValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment