Created
September 11, 2017 03:04
-
-
Save ha1f/1cc0f5dc61257de1295bf926c6d17673 to your computer and use it in GitHub Desktop.
randomString
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 | |
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