https://cloud.tencent.com/developer/article/1794757
https://github.com/apple/swift-protobuf
ProtocolBuf Swift 使用
环境搭建
Mac安装swift-protobuf
brew install swift-protobuf
使用Podfile集成Xcode
再Podfile里添加
pod 'SwiftProtobuf'
然后在此目录下打开terminal运行
Pod install
使用
新建BookInfo.proto
syntax = "proto3";
message BookInfo {
int64 id = 1;
string title = 2;
string author = 3;
}
在此文件同目录下执行下面命令,生成.swift文件
protoc --swift_out=. BookInfo.proto
将.swift文件拖入工程,编译一下,使用
// 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)
标签:info,Data,Swift,BookInfo,try,let,使用,ProtocolBuf,swift
From: https://www.cnblogs.com/itlover2013/p/17137342.html