Generate a UUID on iOS from Swift

前端 未结 6 1731
一向
一向 2020-12-12 09:20

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 = CFUU         


        
相关标签:
6条回答
  • 2020-12-12 09:59

    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.

    0 讨论(0)
  • 2020-12-12 10:03

    Also you can use it lowercase under below

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

    Output

    68b696d7-320b-4402-a412-d9cee10fc6a3

    Thank you !

    0 讨论(0)
  • 2020-12-12 10:05

    Try this one:

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

    Swift 3/4/5

    let uuid = UUID().uuidString
    print(uuid)
    
    0 讨论(0)
  • 2020-12-12 10:11

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

    0 讨论(0)
  • 2020-12-12 10:12

    For Swift 4;

    let uuid = NSUUID().uuidString.lowercased()
    
    0 讨论(0)
  • 2020-12-12 10:23

    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)
    
    0 讨论(0)
提交回复
热议问题