Skip to content

Instantly share code, notes, and snippets.

@jubishop
Created August 18, 2025 05:05
Show Gist options
  • Save jubishop/93d18654966adf79027a39d5a7a01a3a to your computer and use it in GitHub Desktop.
Save jubishop/93d18654966adf79027a39d5a7a01a3a to your computer and use it in GitHub Desktop.
String hash
extension String {
// MARK: - Hashing
func hash(to length: Int = 8) -> String {
guard length > 0 else { return "" }
let data = self.data(using: .utf8)!
let hash = SHA256.hash(data: data)
let hashData = Data(hash)
let chars = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
let result = (0..<length)
.map { i in
let byte = hashData[i % hashData.count]
let index = Int(byte) % chars.count
return chars[index]
}
return String(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment