从 Swift 在 iOS 上生成 UUID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24428250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate a UUID on iOS from Swift
提问by zacjordaan
In my iOS Swift app I want to generate random UUID (GUID) strings for use as a table key, and this snippet appearsto work:
在我的 iOS Swift 应用程序中,我想生成随机 UUID ( GUID) 字符串以用作表键,并且此代码段似乎有效:
let uuid = CFUUIDCreateString(nil, CFUUIDCreate(nil))
Is this safe?
这安全吗?
Or is there perhaps a better (recommended) approach?
或者是否有更好的(推荐的)方法?
回答by Ahmed Al Hafoudh
Try this one:
试试这个:
let uuid = NSUUID().uuidString
print(uuid)
Swift 3/4/5
迅捷 3/4/5
let uuid = UUID().uuidString
print(uuid)
回答by James Frost
回答by Celil Bozkurt
For Swift 4;
对于Swift 4;
let uuid = NSUUID().uuidString.lowercased()
回答by Scott H
For Swift 3, many Foundation
types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString
.
对于 Swift 3,许多Foundation
类型都删除了“NS”前缀,因此您可以通过UUID().uuidString
.
回答by SwiftDeveloper
Also you can
use it lowercase
under below
你can
也可以lowercase
在下面使用它
let uuid = NSUUID().UUIDString.lowercaseString
print(uuid)
Output
输出
68b696d7-320b-4402-a412-d9cee10fc6a3
68b696d7-320b-4402-a412-d9cee10fc6a3
Thank you !
谢谢 !
回答by iAleksandr
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)