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!

Image of Wix Studio

2025: Your year to build apps that sell

Dive into hands-on resources and actionable strategies designed to help you build and sell apps on the Wix App Market.

Get started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay