ProtocolBuf Swift Usage#
Environment Setup#
Install swift-protobuf on Mac.
brew install swift-protobuf
Integrate with Xcode using Podfile#
Add the following line to your Podfile:
pod 'SwiftProtobuf'
Then, open the terminal in this directory and run:
pod install
Usage#
Create a new file called BookInfo.proto
syntax = "proto3";
message BookInfo {
int64 id = 1;
string title = 2;
string author = 3;
}
In the same directory as this file, execute the following command to generate the .swift file:
protoc --swift_out=. BookInfo.proto
Drag the .swift file into your project, compile it, and use it as follows:
// 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)
}