String((0..<length).map { _ in letters.randomElement()! }) where letters contains your allowed characters. For older versions, use arc4random_uniform with character indexing.Why this happens
Generating random strings is a common need for API keys, session tokens, test data, and temporary filenames. Swift’s standard library didn’t include a dedicated random string API until Swift 4.2 introduced randomElement() on collections. Before that, developers had to bridge to C’s arc4random_uniform and manually index into character arrays.
The modern approach uses Swift’s native random API which is cryptographically stronger on Apple platforms (using arc4random_buf internally) and works directly with String and Collection types without unsafe pointer manipulation.
How to fix it
1. Modern Swift 4.2+ (recommended)
This is the cleanest, most readable solution. It uses Collection.randomElement() introduced in Swift 4.2.
func randomAlphanumericString(length: Int) -> String {
let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).compactMap { _ in characters.randomElement() })
}
// Usage
let token = randomAlphanumericString(length: 16)
print(token) // e.g., "7xK9mP2qR4vL8wX1"
Why compactMap? randomElement() returns an optional (Element?). compactMap unwraps and discards nil — though with a non-empty collection it never returns nil.
2. Reusable String extension
Add this to a shared utilities file for project-wide access.
extension String {
static func randomAlphanumeric(length: Int) -> String {
let chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).compactMap { _ in chars.randomElement() })
}
}
// Usage
let id = String.randomAlphanumeric(length: 10)
3. Custom character sets
Need hex-only, alphabetic-only, or symbol-inclusive strings? Parameterize the character pool.
func randomString(length: Int, allowedCharacters: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") -> String {
guard !allowedCharacters.isEmpty, length > 0 else { return "" }
return String((0..<length).compactMap { _ in allowedCharacters.randomElement() })
}
// Examples
let hex = randomString(length: 8, allowedCharacters: "0123456789abcdef")
let alpha = randomString(length: 6, allowedCharacters: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
let withSymbols = randomString(length: 12, allowedCharacters: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_")
4. Legacy Swift 3 / 4.0 (if you must)
Only use this if you’re maintaining code that cannot compile with Swift 4.2+.
func randomAlphanumericStringLegacy(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var result = ""
let count = UInt32(letters.count)
for _ in 0..<length {
let randomIndex = Int(arc4random_uniform(count))
let charIndex = letters.index(letters.startIndex, offsetBy: randomIndex)
result.append(letters[charIndex])
}
return result
}
Note: arc4random_uniform is not cryptographically secure. For security-sensitive tokens (API keys, password reset tokens), see the prevention section.
How to prevent it
- Use the modern API —
randomElement()is faster, safer, and more readable thanarc4random_uniform. - Avoid
NSStringbridging — the legacy answers useNSString/NSMutableString; pure SwiftStringis preferred. - For cryptographic needs, use
SecKeyCreateRandomKeyorCryptoKit‘sSymmetricKey/ChaChaPolyinstead of alphanumeric strings. - Validate length — guard against zero or negative lengths to avoid empty strings or crashes.
- Consider
UUID().uuidString— for unique identifiers, a UUID is often better than a custom random string.
FAQ
Is randomElement() cryptographically secure?
On Apple platforms, randomElement() uses the system CSPRNG (via arc4random_buf), making it suitable for most non-cryptographic uses like test data, filenames, and display IDs. For secrets (API keys, auth tokens), use CryptoKit or Security framework APIs.
Can I use this in a for loop for better performance?
The map/compactMap approach allocates an intermediate array. For very long strings (thousands of characters), a for loop appending to a String with reserveCapacity(length) avoids that allocation. For typical lengths (< 100), the difference is negligible.
Why does the legacy code use UInt32?
arc4random_uniform takes and returns UInt32. The legacy code casts the character count to UInt32 to match the C API, then casts back to Int for Swift indexing. The modern API handles all of this automatically.
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.
