[英]Serialization of Structs to NSData in Swift
I need to save a Swift struct to NSData
. 我需要将Swift结构保存到
NSData
。 I can't conform to NSCoding
since it only works for subclasses of NSObject
. 我无法符合
NSCoding
因为它只适用于NSObject
子类。
I wrote a little protocol
with extensions in Swift 2.0 that seems to work in a Playground. 我在Swift 2.0中编写了一个带有扩展的小
protocol
,似乎可以在Playground中运行。 It seems a little too easy. 这似乎有点太容易了。
Is there something here I am missing? 这里有什么东西我不见了吗?
The following code can be run in a playground in Xcode 7 Beta 5. 以下代码可以在Xcode 7 Beta 5的操场上运行。
//: Playground - noun: a place where people can play
import UIKit
protocol Serializable {
init?(encodedData: NSData)
var encodedData: NSData { get }
}
extension Serializable {
var encodedData: NSData {
var pointer = self
return NSData(bytes: &pointer, length: sizeof(Self.self))
}
init?(encodedData data: NSData) {
guard
data.length == sizeof(Self.self)
else { return nil }
self = UnsafePointer(data.bytes).memory
}
}
struct Test: CustomStringConvertible, Serializable {
let message: String
let people: [String]
let color: UIColor
var description: String {
return "\(message) + \(people) + \(color)"
}
}
let structToEncode = Test(message: "Hi!", people: ["me", "someone else"], color: UIColor(red: 0.5, green: 0.2, blue: 0.1, alpha: 0.4))
let encodedData = structToEncode.encodedData
let decodedStruct = Test(encodedData: encodedData)
I've been looking at a serialization solution for Swift too. 我一直在寻找Swift的序列化解决方案。 Instead of inventing your own protocol, take a look at RawRepresentable.
不要发明自己的协议,而是看看RawRepresentable。 It is more generic than what you are doing here in that it isn't tied to NSData.
它比你在这里做的更通用,因为它不依赖于NSData。 You could serialize to anything as long as your type specifies it in the RawValue type alias.
只要您的类型在RawValue类型别名中指定它,您就可以序列化为任何内容。
Another solution is to serialize your data to JSON. 另一种解决方案是将数据序列化为JSON。 I just created a pod that makes this simpler, and it should work for structs, enums, and classes.
我刚刚创建了一个使这个更简单的pod ,它应该适用于结构,枚举和类。 To use it, you need to implement the
ToJSON
and FromJSON
protocols. 要使用它,您需要实现
ToJSON
和FromJSON
协议。 Then to serialize and deserialize data, you can use the Aeson.encode
and Aeson.decode
functions. 然后,为了序列化和反序列化数据,您可以使用
Aeson.encode
和Aeson.decode
函数。
I wrote a framework to serialize structs, classes and enums in Swift, though it serializes to plist files (exclusively for convenience, could be any format). 我编写了一个框架来序列化Swift中的结构,类和枚举,尽管它序列化为plist文件(仅为方便起见,可以是任何格式)。
High level notes: 高级笔记:
toDictionary()
methods via protocol extensions. toDictionary()
方法的AnyObject表示。 Nothing you have to do to support this side of things. Here's a writeup about the framework , and a link to the github repo . 这是关于框架的文章 ,以及github repo的链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.