Generowanie identyfikatora UUID na iOS z Swift

W mojej aplikacji Swift na iOS chcę wygenerować losowe ciągi znaków uuid (GUID ) do użycia jako klucz tabeli, a ten fragment pojawia się do działania:

let uuid = CFUUIDCreateString(nil, CFUUIDCreate(nil))
Czy to bezpieczne?

A może istnieje lepsze (zalecane) podejście?

Author: Josh Caswell, 2014-06-26

5 answers

Spróbuj tego:

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

Swift 3

let uuid = UUID().uuidString
print(uuid)
 499
Author: Ahmed Al Hafoudh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-08 12:14:52

Możesz również użyć API NSUUID :

let uuid = NSUUID()

Jeśli chcesz odzyskać wartość ciągu, możesz użyć uuid.UUIDString.

Zauważ, że NSUUID jest dostępny od iOS 6 i nowszych.

 27
Author: James Frost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-26 10:45:27

Dla Swift 4;

let uuid = NSUUID().uuidString.lowercased()
 12
Author: Celil Bozkurt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-03 21:20:59

Dla Swift 3, wiele typów Foundation zrzuciło prefiks 'NS', więc można uzyskać do niego dostęp przez UUID().uuidString.

 10
Author: Scott H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-29 21:38:42

Również Ty can Użyj go lowercase poniżej

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

Wyjście

68b696d7-320B-4402-a412-d9cee10fc6a3

Dziękuję !
 5
Author: SwiftDeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-26 11:19:53