将字符串验证为 Swift 中的有效 UUID

Verify a string as a valid UUID in Swift

给定提供的 String,我如何验证 String 是否是 Swift 中的有效 UUID?

有效的 UUID(据我所知)可以是:

33041937-05b2-464a-98ad-3910cbe0d09e
3304193705b2464a98ad3910cbe0d09e

您可以使用 UUID

var uuid = UUID(uuidString: yourString)

如果 yourString 不是有效的 UUID

,这将 return 为零

注意:这仅验证您提供的第一个案例,而不是第二个案例,但您自己添加破折号是微不足道的。

以下内容针对 Swift 4.0 进行了更新,以确定字符串是否为有效的 UUID。

let uuidHyphens = "33041937-05b2-464a-98ad-3910cbe0d09e"
let uuidNoHyphens = "3304193705b2464a98ad3910cbe0d09e"

if UUID(uuidString: uuidHyphens) != nil {
    print("UUID string with hypens is valid") // Will be valid
} else {
    print("UUID string with hypens is not valid")
}

// In this scenario, the UUID will be nil,
if UUID(uuidString: uuidNoHyphens) != nil {
    print("UUID string with no hypens is valid")
} else {
    print("UUID string with no hypens is not valid") // Will not be valid
}

传递给 UUID init must contain hyphens, otherwise the check will fail. If you are expecting strings without hypens, then you can utilize an approach such as what is discussed here 的字符串,如果它满足 32 的长度,则向字符串添加连字符。

A​​pple 文档中的相关部分:

Create a UUID from a string such as “E621E1F8-C36C-495A-93FC-0C247A3E6E5F”.

我写了下面的扩展来制作 UUID 字符串

extension String {
  var uuid: String? {
    var string = self
    var index = string.index(string.startIndex, offsetBy: 8)
    for _ in 0..<4 {
      string.insert("-", at: index)
      index = string.index(index, offsetBy: 5)
    }
    // The init below is used to check the validity of the string returned.
    return UUID(uuidString: string)?.uuidString
  }
}