2016-03-16 145 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崩溃。 –