Created
August 18, 2025 05:05
-
-
Save jubishop/93d18654966adf79027a39d5a7a01a3a to your computer and use it in GitHub Desktop.
String hash
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
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