DEV Community

Sufiyan
Sufiyan

Posted on

Generating a non-random UUID, using a hash of multiple strings in Swift

I was just working with some messy data, and realized I need a deterministic way to generate UUIDs from 2 strings in an iOS project. Looks like the only standard method available is

UUID(uuidString: String)

The problem with this is sometimes we don't have the formatted uuidString, so turns out we need to build it ourselves.

Enough talk, here's the code:

import Foundation
import CommonCrypto

func createHash(from string1: String, and string2: String) -> Data {
    let concatenatedString = string1 + string2
    guard let data = concatenatedString.data(using: .utf8) else {
        return Data()
    }

    var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
    _ = data.withUnsafeBytes {
        CC_SHA256($0.baseAddress, UInt32(data.count), &digest)
    }

    return Data(digest)
}

func generateNonRandomUUID(from string1: String, and string2: String) -> UUID {
    let hashData = createHash(from: string1, and: string2)

    // Truncate the hash data to 128 bits (16 bytes)
    let truncatedHashData = hashData.prefix(16)

    // Create a byte array (UnsafePointer<UInt8>) from the truncated hash data
    var byteArray: [UInt8] = []
    truncatedHashData.withUnsafeBytes {
        byteArray.append(contentsOf: $0)
    }

    // Create a UUID from the byte array
    let uuid = NSUUID(uuidBytes: byteArray)

    return uuid as UUID
}
Enter fullscreen mode Exit fullscreen mode

Happy coding!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay