2016-03-16 194 views
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) 

回答

1

答:的問題是,您聲明encode作爲非突變的功能,但其實現爲不同誘變作用(在所提供的代碼中)。

encode的聲明(在協議中)從func encode() -> NSData改爲mutating func encode() -> NSData以符合您的需求。

+0

非常感謝。我想知道爲什麼它會讓Playground崩潰並且沒有錯誤。 – 100mango

+1

我會建議[創建一個雷達](https://bugreport.apple.com)的Playground崩潰。 –