- Notifications
You must be signed in to change notification settings - Fork488
Plugin and runtime library for using protobuf with Swift
License
apple/swift-protobuf
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Welcome to Swift Protobuf!
Apple's Swift programming language is a perfectcomplement toGoogle's Protocol Buffer("protobuf") serialization technology.They both emphasize high performance and programmer safety.
This project provides both the command-line program that adds Swiftcode generation to Google'sprotoc
and the runtime library that isnecessary for using the generated code.After using the protoc plugin to generate Swift code from your .protofiles, you will need to add this library to your project.
SwiftProtobuf offers many advantages over alternative serializationsystems:
- Safety: The protobuf code-generation system avoids theerrors that are common with hand-built serialization code.
- Correctness: SwiftProtobuf passes both its own extensivetest suite and Google's full conformance test for protobufcorrectness.
- Schema-driven: Defining your data structures in a separate
.proto
schema file clearly documents your communicationsconventions. - Idiomatic: SwiftProtobuf takes full advantage of the Swift language.In particular, all generated types provide full Swift copy-on-writevalue semantics.
- Efficient binary serialization: The
.serializedBytes()
method returns a bag of bytes with a compact binary form of your data.You can deserialize the data using theinit(contiguousBytes:)
initializer. - Standard JSON serialization: The
.jsonUTF8Bytes()
method returns a JSONform of your data that can be parsed with theinit(jsonUTF8Bytes:)
initializer. - Hashable, Equatable: The generated struct can be put into a
Set<>
orDictionary<>
. - Performant: The binary and JSON serializers have beenextensively optimized.
- Extensible: You can add your own Swift extensions to anyof the generated types.
Best of all, you can take the same.proto
file and generateJava, C++, Python, or Objective-C for use on other platforms. Thegenerated code for those languages will use the exact sameserialization and deserialization conventions as SwiftProtobuf, makingit easy to exchange serialized data in binary or JSON forms, with noadditional effort on your part.
More information is available in the associated documentation:
- Google's protobuf documentationprovides general information about protocol buffers, the protoc compiler,and how to use protocol buffers with C++, Java, and other languages.
- PLUGIN.md documents the
protoc-gen-swift
plugin that adds Swift support to theprotoc
program - API.md documents how to use the generated code.This is recommended reading for anyone using SwiftProtobuf in theirproject.
- INTERNALS.md documents the internal structureof the generated code and the library. Thisshould only be needed by folks interested in working on SwiftProtobufitself.
- STYLE_GUIDELINES.md documents the styleguidelines we have adopted in our codebase if you are interested incontributing
If you've worked with Protocol Buffers before, adding Swift support is verysimple: you just need to build theprotoc-gen-swift
program and copy it intoyour PATH.Theprotoc
program will find and use it automatically, allowing youto build Swift sources for your proto files.You will also, of course, need to add the SwiftProtobuf runtime library toyour project as explained below.
To use Swift with Protocol buffers, you'll need:
A Swift 5.10 or later compiler (or, if building with Xcode, Xcode 15.3 or lateras required by the App Store). The Swift protobuf project is being developedand tested against the latest release version of Swift available fromSwift.org
Google's protoc compiler. The Swift protoc plugin is being actively developedand tested against the latest protobuf sources. The SwiftProtobuf tests need aversion of protoc which supports the
swift_prefix
option (introduced inprotoc 3.2.0). It may work with earlier versions of protoc. You can get recentversions fromGoogle's github repository.
To translate.proto
files into Swift, you will need both Google'sprotoc compiler and the SwiftProtobuf code generator plugin.
Building the plugin should be simple on any supported Swift platform:
git clone https://github.com/apple/swift-protobuf.gitcd swift-protobuf
Pick what released version of SwiftProtobuf you are going to use. You can geta list of tags with:
git tag -l
Once you pick the version you will use, set your local state to match, andbuild the protoc plugin:
git checkout tags/[tag_name]swift build -c release
This will create a binary calledprotoc-gen-swift
in the.build/release
directory.
To install, just copy this one executable into a directory that ispart of yourPATH
environment variable.
NOTE: The Swift runtime support is now included with macOS. If you areusing old Xcode versions or are on older system versions, you might needto use also use--static-swift-stdlib
withswift build
.
If you prefer usingHomebrew:
brew install swift-protobuf
This will installprotoc
compiler and Swift code generator plugin.
To generate Swift output for your .proto files, you run theprotoc
command asusual, using the--swift_out=<directory>
option:
protoc --swift_out=. my.proto
Theprotoc
program will automatically look forprotoc-gen-swift
in yourPATH
and use it.
Each.proto
input file will get translated to a corresponding.pb.swift
file in the output directory.
More information about building and usingprotoc-gen-swift
can be foundin thedetailed Plugin documentation.
To use the generated code, you need to include theSwiftProtobuf
librarymodule in your project. How you do this will vary depending on howyou're building your project. Note that in all cases, we strongly recommendthat you use the version of the SwiftProtobuf library that corresponds tothe version ofprotoc-gen-swift
you used to generate the code.
After copying the.pb.swift
files into your project, you will need to add theSwiftProtobuf library to yourproject to support the generated code.If you are using the Swift Package Manager, add a dependency to yourPackage.swift
file and import theSwiftProtobuf
library into the desiredtargets. Adjust the"1.27.0"
here to match the[tag_name]
you used to buildthe plugin above:
dependencies:[.package(url:"https://github.com/apple/swift-protobuf.git", from:"1.27.0"),],targets:[.target( name:"MyTarget", dependencies:[.product(name:"SwiftProtobuf",package:"swift-protobuf")]),]
If you are using Xcode, then you should:
- Add the
.pb.swift
source files generated from your protos directly to yourproject - Add this SwiftPM package as dependency of your xcode project:Apple Docs
If you're using CocoaPods, add this to yourPodfile
adjusting the:tag
tomatch the[tag_name]
you used to build the plugin above:
pod'SwiftProtobuf','~> 1.0'
And runpod install
.
NOTE: CocoaPods 1.7 or newer is required.
Once you have installed the code generator, used it togenerate Swift code from your.proto
file, andadded the SwiftProtobuf library to your project, you canjust use the generated types as you would any other Swiftstruct.
For example, you might start with the following very simpleproto file:
syntax="proto3";messageBookInfo {int64id=1;stringtitle=2;stringauthor=3;}
Then generate Swift code using:
protoc --swift_out=. DataModel.proto
The generated code will expose a Swift property foreach of the proto fields as well as a selectionof serialization and deserialization capabilities:
// Create a BookInfo object and populate it:varinfo=BookInfo()info.id=1734info.title="Really Interesting Book"info.author="Jane Smith"// As above, but generating a read-only value:letinfo2=BookInfo.with{ $0.id=1735 $0.title="Even More Interesting" $0.author="Jane Q. Smith"}// Serialize to binary protobuf format: you can choose to serialize into// any type conforming to `SwiftProtobufContiguousBytes`. For example:// Resolve the `SwiftProtobufContiguousBytes` return value to `Data`letbinaryData:Data=try info.serializedBytes()// Resolve the `SwiftProtobufContiguousBytes` return value to `[UInt8]`letbinaryDataAsBytes:[UInt8]=try info.serializedBytes()// Note that while the `serializedBytes()` spelling is generally preferred,// you may also use `serializedData()` to get the bytes as an instance of // `Data` where required.// This means that the following two statements are equivalent:// let binaryData: Data = try info.serializedBytes()// let binaryData: Data = try info.serializedData()// Deserialize a received Data object from `binaryData`letdecodedInfo=tryBookInfo(serializedData: binaryData)// Deserialize a received [UInt8] object from `binaryDataAsBytes`letdecodedInfo=tryBookInfo(serializedBytes: binaryDataAsBytes)// Serialize to JSON format as a Data object, or as any other type conforming to// SwiftProtobufContiguousBytes. For example:letjsonData:Data=try info.jsonUTF8Data()letjsonBytes:[UInt8]=try info.jsonUTF8Bytes()// Deserialize from JSON format from `jsonBytes`letreceivedFromJSON=tryBookInfo(jsonUTF8Bytes: jsonBytes)
You can find more information in the detailedAPI Documentation.
If you run into problems, please send us a detailed report.At a minimum, please include:
- The specific operating system and version (for example, "macOS 10.12.1" or"Ubuntu 16.10")
- The version of Swift you have installed (from
swift --version
) - The version of the protoc compiler you are working with from
protoc --version
- The specific version of this source code (you can use
git log -1
to get thelatest commit ID) - Any local changes you may have
About
Plugin and runtime library for using protobuf with Swift
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.