Generating a unique identifier is easy thanks to Foundation's UUID
struct. In this episode of Swift Fundamentals, you learn how to create an identifier that is (almost) guaranteed to be unique.
Creating a Unique Identifier
There are plenty of scenarios in which you need a unique identifier. I typically generated a unique identifier for Core Data records to avoid conflicts on the backend. Let me show you how that works.
The start of the story is the UUID
struct. This type was introduced many years ago and has made it trivial to address this common need. Fire up Xcode and create a playground by choosing the Blank template from the iOS > Playground section if you want to follow along.
Add an import statement for Foundation because the UUID
struct is defined in Foundation. We create a UUID
object.
import Foundation
let uuid = UUID()
In most use cases, you need the UUID as a string, for example, if you send the UUID to a server. You can access the string representation of the UUID
object through its uuidString
property.
import Foundation
let uuid = UUID()
uuid.uuidString // E0B1B7FD-61A8-49F1-8729-B628D42396D4
The UUID (universally unique identifier) conforms to RFC 4122, and you are unlikely to ever create the same UUID. That's the idea underlying the UUID
struct.
Core Data
A few years ago, Apple added support for UUIDs to Core Data. You can set the type of an attribute to UUID in Core Data's data model editor.
Remember that a Core Data attribute of type UUID corresponds to a property of type UUID
. The UUID isn't of type String
.
Encoding and Decoding
The good news is that the UUID
struct conforms to the Encodable
and Decodable
protocols, Codable
for short. It is trivial to convert an object with a property of type UUID
to, for example, JSON.
import Foundation
struct Book: Codable {
// MARK: - Properties
let uuid: UUID
let title: String
}
let book = Book(
uuid: UUID(),
title: "The Hobbit"
)
If we encode the Book
object to JSON using a JSONEncoder
instance, the UUID
object is converted to a String
.
{
"uuid": "7B4F7C20-4127-444C-A168-F4A1A88C2213",
"title": "The Hobbit"
}
Converting the UUID from a string is also supported thanks to an initializer that accepts a string as an argument.
let uuidAsString = "E0B1B7FD-61A8-49F1-8729-B628D42396D4"
let uuid = UUID(uuidString: uuidAsString)
What's Next?
The UUID
struct is a nice, little helper that does a few things, but it does them very well. It avoids the need to develop your own implementation to generate unique identifiers or rely on a third party solution.