在撰写此问题时,我使用的是 Swift 2.1 和 Xcode 7.2.1。
下面的代码(用于编码 a struct
)不起作用并使 Xcode 游乐场崩溃而没有错误。在项目中,它会在编译期间导致分段错误。
protocol StructCoding {
typealias structType
func encode() -> NSData
static func decode(data: NSData) -> Self
}
extension StructCoding {
mutating func encode() -> NSData {
return withUnsafePointer(&self) { p in
NSData(bytes: p, length: sizeofValue(self))
}
}
static func decode(data: NSData) -> structType {
let pointer = UnsafeMutablePointer<structType>.alloc(sizeof(structType))
data.getBytes(pointer, length: sizeof(structType))
return pointer.move()
}
}
struct testStruct: StructCoding {
let a = "dsd"
let b = "dad"
typealias structType = testStruct
}
但这些可以工作。
struct testStruct: StructCoding {
let a = "dsd"
let b = "dad"
mutating func encode() -> NSData {
return withUnsafePointer(&self) { p in
NSData(bytes: p, length: sizeofValue(self))
}
}
static func decode(data: NSData) -> testStruct {
let pointer = UnsafeMutablePointer<testStruct>.alloc(sizeof(testStruct))
data.getBytes(pointer, length: sizeof(testStruct))
return pointer.move()
}
}
var s1 = testStruct()
let data = s1.encode()
let s2 = testStruct.decode(data)