我有兴趣创建一个经过修改的编码UUID,但我有一段时间才能获得正确的格式。我目前没有编译的原因不明但奇怪的是我能够在操场上运行它。这是功能:
class func genID() -> String {
let uuid = NSUUID.UUID()
let data = NSData(bytes:&uuid, length:16)
let base64 = data.base64EncodedStringWithOptions(nil)
let options = NSStringCompareOptions.LiteralSearch
let result = base64
.stringByReplacingOccurrencesOfString("/", withString: "-", options: options, range: nil)
.stringByReplacingOccurrencesOfString("+", withString: "_", options: options, range: nil)
.stringByReplacingOccurrencesOfString("=", withString: "", options: options, range: nil)
return result
}
问题在功能的第二行标记;创建数据值。奇怪的是,这条线在游乐场中起作用。任何帮助,将不胜感激。那我在这里错过了什么?
提前致谢。
答案 0 :(得分:3)
您可以使用
从NSData
创建NSUUID
对象
let uuid = NSUUID.UUID()
// data object with appropriate size:
let data = NSMutableData(length: 16)
// fill the bytes from the UUID:
uuid.getUUIDBytes(UnsafeMutablePointer(data.mutableBytes))
答案 1 :(得分:1)
通过将uuid_t类型转换为Data对象,我可以在不使用NSUUID的情况下执行此操作。此类型是16字节元组的别名。在实现中看起来有点奇怪,但它确实有效,如果由于某种原因uuid_t类型发生变化,这是相当未来的证明。这是我创建的UUID扩展:
extension UUID {
var base64String: String {
return self.data.base64EncodedString()
}
var data: Data {
var result = Data()
let uuidTuple = self.uuid
// NOTE: There are clever ways to iterate over a tuple in Swift,
// but I actually want this to not compile if the implementation of uuid_t
// changes in the future
result.append(uuidTuple.0)
result.append(uuidTuple.1)
result.append(uuidTuple.2)
result.append(uuidTuple.3)
result.append(uuidTuple.4)
result.append(uuidTuple.5)
result.append(uuidTuple.6)
result.append(uuidTuple.7)
result.append(uuidTuple.8)
result.append(uuidTuple.9)
result.append(uuidTuple.10)
result.append(uuidTuple.11)
result.append(uuidTuple.12)
result.append(uuidTuple.13)
result.append(uuidTuple.14)
result.append(uuidTuple.15)
return result
}
}