2
截至寫這個問題的時候,我正在使用Swift 2.1和Xcode 7.2.1。協議擴展不起作用(Swift)
下面的代碼(意爲編碼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)
非常感謝。我想知道爲什麼它會讓Playground崩潰並且沒有錯誤。 – 100mango
我會建議[創建一個雷達](https://bugreport.apple.com)的Playground崩潰。 –