Let’s learn how to make UUIDs in Swift.
UUID stands for a universally unique identifier. Its guaranteed to be unique across all devices in the world.
This is great when you need to reference something individually and not have to worry if it’s unique.
In swift, we can create simply be using the UUID()
call:
import Foundation
let uuid = UUID().uuidString
print(uuid)
This will print:
F3E2169B-EB75-4DA4-81FD-A9E5C863DA63
Of course what prints to your console will be different, because they’re unique of course!
Adding UUID as a property to a class can be a great idea. This allows you to uniquely identify each object.
import Foundation
class Person {
let uuid = UUID().uuidString
var firstName: String?
var lastName: String?
var age: Int?
}
UUIDs are universally unique identifiers. So they’re especially useful when data will be shared across multiple databases and many different applications.
This ensures that the objects will remain unique, no matter what environment or setup they’re accessed from.
If you think your application will scale to a large amount of objects, UUIDs can be a good choice.
If your application writes and reads from a single database, a UUID is not necessary and can decrease the performance of your database greatly.
During inserts, an integer ID may be preferred to a UUID.
Let’s say you have student objects. If each of these student objects already have a unique student id assigned by the school, there is no reason to use another identifier such as a UUID.
This will add unnecessary complexity to your app and is a poor design choice.
If you are going to present the ID to the end user, such as on their profile page or another page, UUID is not a good idea.
Just look at F3E2169B-EB75-4DA4-81FD-A9E5C863DA63
. It’s not very readable and it would be much more suitable to give the user a 3 or 6 digit id number instead.
UUIDs are standardized by the Open Software Foundation. The Internet Engineering Task Force published the standard as RFC 4122.
The probability of a collision within 103 trillion version-4 UUIDs is one in a billion. This is extremely rare, but there is a non-zero chance.
Version 4 of the UUID standard is generated using random numbers and is the current recommended version.
Of course if there’s already a logical key, such as a staff number or driver’s license number, use that instead.
Incremental integers can be used if the objects will be limited in scope and only be read/write by one database. You can simply assign 1, to the first object, 2 to the second and so on.
ULID - Universally Unique Lexicographically Sortable Identifier, is a new proposed identifier. Read more here
You should be aware of the security concerns, collision probability and performance of any alternatives.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.