UUID().uuidString to generate a UUID string, or UUID() to keep the value as a UUID. For table keys and SwiftUI model identifiers, generate the UUID once when creating the record and persist it with that record.Why this happens
Swift exposes several ways to create a UUID, which can make older examples confusing. Core Foundation provides CFUUIDCreate, Objective-C code commonly uses NSUUID, and modern Swift uses Foundation’s UUID value type. These APIs address the same basic need: creating an identifier without maintaining a shared counter.
The original expression, CFUUIDCreateString(nil, CFUUIDCreate(nil)), uses valid Core Foundation APIs. You do not need to replace it because it inherently creates an invalid identifier. However, it introduces Core Foundation types and allocator arguments for a task that Foundation handles directly in Swift.
For table keys and SwiftUI lists, generating the value is only half the solution. The identifier must remain attached to the same record. A fresh UUID every time a view updates or a property is read creates a new identity rather than preserving an existing one.
How to fix it
1. Generate a UUID with Foundation
Use UUID() in modern Swift. If the receiving API expects a string, access its uuidString property:
import Foundation
let identifier = UUID()
let stringKey = identifier.uuidString
print(stringKey)
For a string-only use case, the accepted solution reduces to one line:
import Foundation
let stringKey = UUID().uuidString
Choose the representation based on where the value goes:
- Use
UUIDfor an in-memory model property when the surrounding APIs support it. - Use
Stringwhen a database column, request field, or other interface explicitly requires text. - Convert an existing UUID with
.uuidString; do not create another UUID just to obtain a string representation.
Each call to UUID() requests a new identifier. Reading identifier.uuidString repeatedly converts the same stored identifier instead.
2. Give each record a stored identifier
For a table key, create the UUID when you create the record. Do not generate it whenever you ask for that record’s ID.
This model keeps its identity separate from its editable content:
import Foundation
struct Record: Identifiable, Codable {
let id: UUID
var title: String
init(id: UUID = UUID(), title: String) {
self.id = id
self.title = title
}
}
A new record receives a UUID automatically:
var record = Record(title: "First draft")
let originalID = record.id
record.title = "Updated draft"
assert(record.id == originalID)
The explicit initializer also lets you reconstruct a record with an existing ID, such as one loaded from storage or supplied by a server.
Avoid making the identifier a computed property:
import Foundation
struct UnstableRecord: Identifiable {
var title: String
// Incorrect for persistent record identity.
var id: UUID { UUID() }
}
That property returns a new value on every access. It is not a stable table key, even though each individual UUID is valid.
If your storage layer requires a string key, the same principle applies: store a String initialized with UUID().uuidString once, rather than computing it repeatedly.
3. Let SwiftUI use the model’s stable ID
With the Record model above in the same target, SwiftUI can identify rows directly through Identifiable:
import SwiftUI
struct RecordList: View {
@State private var records: [Record] = [
Record(title: "First record")
]
var body: some View {
VStack {
List(records) { record in
Text(record.title)
}
Button("Add record") {
records.append(Record(title: "New record"))
}
}
}
}
The button creates a new UUID because it creates a new record. Existing records keep their identifiers when the list changes.
Do not add .id(UUID()) to a row to make it identifiable. That supplies a changing view identity whenever the expression is reevaluated. Changing identity can reset state associated with the view rather than helping SwiftUI track the existing row.
Also avoid recreating all your records from display strings during every update. Even a correctly stored let id = UUID() receives a new value when you construct a new model instance. Preserve the models, or reconstruct them with their saved IDs.
4. Persist and validate the identifier
A generated UUID survives an app relaunch only if you save it and load it again. Generating another UUID for the same saved record does not restore its previous identity.
Because the Record model conforms to Codable, its ID can travel with its other data:
import Foundation
func verifyRecordRoundTrip() throws {
let original = Record(title: "Saved record")
let data = try JSONEncoder().encode(original)
let restored = try JSONDecoder().decode(Record.self, from: data)
assert(restored.id == original.id)
}
This demonstrates encoding and decoding; your app still needs to write the data to its chosen storage location.
When an external source supplies a UUID string, parse it with the failable initializer:
import Foundation
func recordID(from text: String) -> UUID? {
UUID(uuidString: text)
}
An invalid string produces nil. Handle that as invalid input rather than force-unwrapping it. Avoid silently substituting UUID() for a malformed existing key: that changes the identity and can disconnect the record from related data.
5. Use NSUUID only when needed for older code
The older Foundation solution remains valid:
import Foundation
let stringKey = NSUUID().uuidString
NSUUID is useful when working with Objective-C APIs or maintaining code that already uses that class. For new Swift code, UUID is the straightforward choice.
Very old Swift examples may spell the property UUIDString. In current Swift, use uuidString. There is no need to introduce Core Foundation allocation calls merely to generate a string key.
How to prevent it
- Generate an ID at record creation, not inside a computed property or view body.
- Keep identity independent of editable fields such as a title or display name.
- Save the UUID alongside the record and restore it unchanged.
- Convert between
UUIDandStringat interface boundaries rather than generating replacement IDs. - Keep a database uniqueness constraint when duplicate keys must be rejected. UUID generation is not a replacement for enforcing storage rules.
FAQ
Is UUID().uuidString safe to use as a table key?
Yes, it is a normal way to generate a UUID string for a record key. Random UUID collisions are extraordinarily unlikely, but uniqueness-sensitive storage should still enforce a unique or primary-key constraint. Generate the value once and retain it for that record.
Should I store the identifier as UUID or String?
Prefer UUID in your Swift model when the surrounding APIs support it, because the type expresses what the value represents. Use a string when your storage schema or external API requires one, and parse incoming strings with UUID(uuidString:) when appropriate.
Does a UUID identify the iPhone or the current installation?
No. Calling UUID() generates a new value; it does not retrieve a device identifier or automatically return the same value on the next launch. If you need an app-defined identifier to remain stable, store it and retrieve that saved value rather than generating it again.
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.
