Generate a UUID on iOS from Swift

你说的曾经没有我的故事 提交于 2019-11-30 06:08:08

问题


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?


回答1:


Try this one:

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

Swift 3/4

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



回答2:


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.




回答3:


For Swift 4;

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



回答4:


For Swift 3, many Foundation types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString.




回答5:


Also you can use it lowercase under below

let uuid = NSUUID().UUIDString.lowercaseString
print(uuid)

Output

68b696d7-320b-4402-a412-d9cee10fc6a3

Thank you !




回答6:


Each time the same will be generated:

if let uuid = UIDevice.current.identifierForVendor?.uuidString {
    print(uuid)
}

Each time a new one will be generated:

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


来源:https://stackoverflow.com/questions/24428250/generate-a-uuid-on-ios-from-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!