Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
randomString
import Foundation
import UIKit
private func arrayBetween(_ c1: String, _ c2: String) -> [UInt32] {
guard let s1 = c1.unicodeScalars.first?.value,
let s2 = c2.unicodeScalars.first?.value else {
return []
}
return (s1 < s2 ? (s1...s2) : (s2...s1)).map { $0 }
}
private func character(from code: UInt32) -> Character? {
return UnicodeScalar(code).map { Character($0) }
}
private func randomCharacter(array: [UInt32]) -> Character? {
let index = Int(arc4random_uniform(UInt32(array.count)))
let code = array[index]
return character(from: code)
}
func randomString(_ length: Int = 1) -> String {
let candidates = arrayBetween("a", "z") + arrayBetween("A", "Z") + arrayBetween("0", "9")
return String((0..<length).flatMap { _ in randomCharacter(array: candidates) })
}
print(randomString(10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment