今是昨非

今是昨非

日出江花红胜火,春来江水绿如蓝

ProtocolBuf Swift Usage

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;
}

Execute the following command in the same directory 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)
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.