Created
August 19, 2020 13:55
-
-
Save willwfsp/ab2f4b5a816c6745c513fef690f5461b to your computer and use it in GitHub Desktop.
Utility to generate random values
This file contains hidden or 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
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