Skip to content
DeveloperMemos

Generating a UUID in Swift

iOS Development, Swift Programming, UUID1 min read

A UUID (Universally Unique Identifier) is a 128-bit value that is unique across time and space. It's commonly used to identify objects, files, or network messages. In this post, we will learn how to generate a UUID in Swift.

Using the UUID Class

Swift has a built-in UUID class that can be used to generate UUIDs. The UUID class can generate four types of UUIDs:

  1. Version 1 UUIDs use a combination of the MAC address of the computer and a timestamp.
  2. Version 2 UUIDs are similar to version 1 UUIDs but include additional information about the user who created the UUID.
  3. Version 3 UUIDs use a namespace and a name to generate the UUID.
  4. Version 4 UUIDs are generated from random numbers.

Generating a Version 4 UUID

To generate a version 4 UUID, you can simply call the UUID() constructor:

1let uuid = UUID()
2print(uuid.uuidString)

This will generate a new UUID and print it to the console.

Generating a Version 3 UUID

To generate a version 3 UUID, you need to specify a namespace and a name. The namespace is typically a UUID that identifies the organization that owns the name. The name is a string that identifies the entity you want to generate the UUID for.

1let namespace = UUID(uuidString: "00000000-0000-0000-0000-000000000000")!
2let name = "example"
3let uuid = UUID(namespace: namespace, name: name)
4print(uuid.uuidString)

This will generate a version 3 UUID based on the namespace and name provided.


In this post, we learned how to generate UUIDs in Swift using the built-in UUID class. We saw how to generate both version 4 and version 3 UUIDs. UUIDs are an important part of many software systems and can be used to uniquely identify entities such as objects, files, or network messages.