Generate a UUID on iOS from Swift
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?
Try this one:
let uuid = NSUUID().UUIDString
print(uuid)
Swift 3
let uuid = UUID().uuidString
print(uuid)
You could also just use the NSUUID API:
let uuid = NSUUID()
If you want to get the string value back out, you can use uuid.UUIDString
.
Note that NSUUID
is available from iOS 6 and up.
对于Swift 3,许多Foundation
类型已经放弃了'NS'前缀,因此您可以通过UUID().uuidString
访问它。
上一篇: UUID在MySQL中的性能?
下一篇: 在iOS上从Swift生成一个UUID