Generate a UUID on iOS from Swift

zacjordaan picture zacjordaan · Jun 26, 2014 · Viewed 150.5k times · Source

In my iOS Swift app I want to generate random UUID (GUID) strings for use as a table key, and this snippet appears to work:

let uuid = CFUUIDCreateString(nil, CFUUIDCreate(nil))

Is this safe?

Or is there perhaps a better (recommended) approach?

Answer

Ahmed Al Hafoudh picture Ahmed Al Hafoudh · Jun 26, 2014

Try this one:

let uuid = NSUUID().uuidString
print(uuid)

Swift 3/4/5

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