Last active
February 4, 2025 05:23
-
-
Save usagimaru/bf7cf97ac19845ac6b081ea6c65171d7 to your computer and use it in GitHub Desktop.
Generating dummy string with random characters in Swift
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 | |
extension String { | |
static func random(in length: UInt, characterSource: [Int]? = nil) -> String { | |
let charcodes: [Int] | |
if let characterSource { | |
charcodes = characterSource | |
} | |
else { | |
let numbers = Array(0x0030...0x0039) | |
let alphabet = Array(0x0041...0x005A) + Array(0x0061...0x007A) | |
charcodes = numbers + alphabet | |
} | |
let dummyLetters = charcodes.compactMap { | |
if let scalar = UnicodeScalar($0) { | |
return String(scalar) | |
} | |
return nil | |
} | |
var dummyString = "" | |
for _ in 0..<length { | |
dummyString += String(dummyLetters.randomElement() ?? "") | |
} | |
return dummyString | |
} |
Author
usagimaru
commented
Feb 4, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment