从 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:06:57  来源:igfitidea点击:

Generate a UUID on iOS from Swift

iosswiftcocoa-touchguidcore-foundation

提问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

You could also just use the NSUUIDAPI:

你也可以只使用NSUUIDAPI:

let uuid = NSUUID()

If you want to get the string value back out, you can use uuid.UUIDString.

如果要取回字符串值,可以使用uuid.UUIDString.

Note that NSUUIDis available from iOS 6 and up.

请注意,NSUUID可从 iOS 6 及更高版本使用。

回答by Celil Bozkurt

For Swift 4;

对于Swift 4;

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

回答by Scott H

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

对于 Swift 3,许多Foundation类型都删除了“NS”前缀,因此您可以通过UUID().uuidString.

回答by SwiftDeveloper

Also you canuse it lowercaseunder 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)