ProtocolBuf Swift 使用
环境搭建
Mac安装swift-protobuf
代码语言:javascript复制brew install swift-protobuf
使用Podfile集成Xcode
再Podfile里添加
代码语言:javascript复制pod 'SwiftProtobuf'
然后在此目录下打开terminal运行
代码语言:javascript复制Pod install
使用
新建BookInfo.proto
代码语言:javascript复制syntax = "proto3";
message BookInfo {
int64 id = 1;
string title = 2;
string author = 3;
}
在此文件同目录下执行下面命令,生成.swift文件
代码语言:javascript复制protoc --swift_out=. BookInfo.proto
将.swift文件拖入工程,编译一下,使用
代码语言:javascript复制// Create a BookInfo object and populate it:
var info = BookInfo()
info.id = 1734
info.title = "Really Interesting Book"
info.author = "Jane Smith"
do {
// Serialize to binary protobuf format:
let binaryData: Data = try info.serializedData()
// Deserialize a received Data object from `binaryData`
let decodedInfo = try BookInfo(serializedData: binaryData)
// Serialize to JSON format as a Data object
let jsonData: Data = try info.jsonUTF8Data()
// Deserialize from JSON format from `jsonData`
let receivedFromJSON = try BookInfo(jsonUTF8Data: jsonData)
} catch {
print(error)
}