Convert Figma logo to code with AI

apple logoswift-protobuf

Plugin and runtime library for using protobuf with Swift

4,563
449
4,563
53

Top Related Projects

Go support for Google's protocol buffers

Protocol Buffers library for idiomatic .NET

Rust implementation of Google protocol buffers

Protocol Buffers implementation in C

Quick Overview

Swift Protobuf is a plugin and runtime library for using Protocol Buffers with Apple's Swift programming language. It provides a Swift API for encoding and decoding protobuf messages, making it easier to work with protobuf data in Swift applications.

Pros

  • Seamless integration with Swift language features and syntax
  • High performance and efficient binary encoding/decoding
  • Strong type safety and compile-time checks
  • Automatic code generation from .proto files

Cons

  • Limited support for some advanced protobuf features
  • Potential compatibility issues with other protobuf implementations
  • Learning curve for developers new to Protocol Buffers
  • Dependency on external tools for code generation

Code Examples

  1. Defining a message in a .proto file:
syntax = "proto3";

message Person {
  string name = 1;
  int32 age = 2;
  repeated string hobbies = 3;
}
  1. Generating Swift code from the .proto file:
protoc --swift_out=. person.proto
  1. Using the generated Swift code:
import Foundation
import SwiftProtobuf

var person = Person()
person.name = "Alice"
person.age = 30
person.hobbies = ["reading", "hiking"]

// Serialize to binary
let binaryData = try person.serializedData()

// Deserialize from binary
let decodedPerson = try Person(serializedData: binaryData)
print(decodedPerson.name) // Output: Alice

Getting Started

  1. Install Swift Protobuf:

    brew install swift-protobuf
    
  2. Add SwiftProtobuf to your project's Package.swift:

    dependencies: [
        .package(url: "https://github.com/apple/swift-protobuf.git", from: "1.19.0"),
    ],
    targets: [
        .target(
            name: "YourTarget",
            dependencies: ["SwiftProtobuf"]
        ),
    ]
    
  3. Generate Swift code from your .proto files:

    protoc --swift_out=. your_proto_file.proto
    
  4. Import and use the generated code in your Swift files:

    import SwiftProtobuf
    // Use your generated message types here
    

Competitor Comparisons

Go support for Google's protocol buffers

Pros of protobuf

  • Mature and widely adopted in the Go ecosystem
  • Excellent performance and efficient serialization
  • Comprehensive support for Protocol Buffers features

Cons of protobuf

  • Less idiomatic Swift code generation
  • May require more manual intervention for Swift-specific optimizations
  • Potentially steeper learning curve for Swift developers

Code Comparison

swift-protobuf:

import SwiftProtobuf

let message = MyMessage()
message.name = "Swift"
message.value = 42

let data = try message.serializedData()

protobuf:

import "github.com/golang/protobuf/proto"

message := &MyMessage{
    Name:  proto.String("Go"),
    Value: proto.Int32(42),
}

data, err := proto.Marshal(message)

Both libraries provide similar functionality for working with Protocol Buffers, but swift-protobuf is tailored specifically for Swift, while protobuf is designed for Go. The swift-protobuf library generates more Swift-idiomatic code, whereas protobuf follows Go conventions. The Go implementation may have a slight edge in performance due to its maturity and optimization for the language.

Protocol Buffers library for idiomatic .NET

Pros of protobuf-net

  • Supports .NET Framework, .NET Core, and .NET Standard, offering broader compatibility
  • Provides attribute-based serialization, allowing for easier integration with existing C# classes
  • Offers runtime code generation, enabling dynamic serialization without pre-generated code

Cons of protobuf-net

  • Limited support for some Protocol Buffers features compared to Swift Protobuf
  • May have slightly lower performance in certain scenarios due to its runtime code generation approach

Code Comparison

Swift Protobuf:

import SwiftProtobuf

let message = MyMessage()
message.id = 123
message.name = "Example"

let data = try message.serializedData()

protobuf-net:

using ProtoBuf;

[ProtoContract]
class MyMessage
{
    [ProtoMember(1)]
    public int Id { get; set; }
    [ProtoMember(2)]
    public string Name { get; set; }
}

var message = new MyMessage { Id = 123, Name = "Example" };
var data = Serializer.Serialize(message);

The code comparison shows that protobuf-net uses attributes to define serialization behavior, while Swift Protobuf relies on generated code from .proto files. protobuf-net's approach allows for easier integration with existing C# classes, but may require more manual configuration.

Rust implementation of Google protocol buffers

Pros of rust-protobuf

  • Better performance and lower memory usage due to Rust's efficiency
  • More mature and feature-complete implementation
  • Supports a wider range of Protocol Buffers features

Cons of rust-protobuf

  • Less seamless integration with the Rust ecosystem compared to Swift's integration
  • May require more manual configuration and setup
  • Documentation could be more comprehensive and user-friendly

Code Comparison

swift-protobuf:

import SwiftProtobuf

let message = MyMessage()
message.name = "John Doe"
message.age = 30

let data = try message.serializedData()

rust-protobuf:

use protobuf::Message;

let mut message = MyMessage::new();
message.set_name("John Doe".to_string());
message.set_age(30);

let data = message.write_to_bytes().unwrap();

Both libraries provide similar functionality for creating and serializing Protocol Buffer messages. The syntax differs slightly due to language differences, but the overall structure is comparable. swift-protobuf leverages Swift's native syntax for property assignment, while rust-protobuf uses setter methods. The rust-protobuf example includes error handling with unwrap(), which is idiomatic in Rust.

Protocol Buffers implementation in C

Pros of protobuf-c

  • Written in C, offering better performance and lower memory footprint
  • Suitable for embedded systems and resource-constrained environments
  • Provides a more direct mapping to Protocol Buffers' wire format

Cons of protobuf-c

  • Less type-safe compared to Swift-Protobuf's strongly-typed approach
  • Requires manual memory management, increasing the risk of memory leaks
  • Limited integration with modern C++ features and standard library

Code Comparison

protobuf-c:

ProtobufCMessage *msg;
size_t len;
uint8_t *buf = protobuf_c_message_pack(msg, &len);
// Use buf, then free it
free(buf);

Swift-Protobuf:

let message = MyMessage()
let data = try message.serializedData()
// Use data, automatically managed by Swift

The protobuf-c example demonstrates manual memory management, while Swift-Protobuf leverages Swift's automatic memory management. Swift-Protobuf also provides a more concise and type-safe API, reducing the likelihood of runtime errors. However, protobuf-c offers finer control over memory allocation and potentially better performance in resource-constrained environments.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Swift logo

Swift Protobuf

Welcome to Swift Protobuf!

Apple's Swift programming language is a perfect complement to Google's Protocol Buffer ("protobuf") serialization technology. They both emphasize high performance and programmer safety.

This project provides both the command-line program that adds Swift code generation to Google's protoc and the runtime library that is necessary for using the generated code. After using the protoc plugin to generate Swift code from your .proto files, you will need to add this library to your project.

Build and Test Check Upstream Protos Run Conformance Tests

Features of SwiftProtobuf

SwiftProtobuf offers many advantages over alternative serialization systems:

  • Safety: The protobuf code-generation system avoids the errors that are common with hand-built serialization code.
  • Correctness: SwiftProtobuf passes both its own extensive test suite and Google's full conformance test for protobuf correctness.
  • Schema-driven: Defining your data structures in a separate .proto schema file clearly documents your communications conventions.
  • Idiomatic: SwiftProtobuf takes full advantage of the Swift language. In particular, all generated types provide full Swift copy-on-write value 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 the init(contiguousBytes:) initializer.
  • Standard JSON serialization: The .jsonUTF8Bytes() method returns a JSON form of your data that can be parsed with the init(jsonUTF8Bytes:) initializer.
  • Hashable, Equatable: The generated struct can be put into a Set<> or Dictionary<>.
  • Performant: The binary and JSON serializers have been extensively optimized.
  • Extensible: You can add your own Swift extensions to any of the generated types.

Best of all, you can take the same .proto file and generate Java, C++, Python, or Objective-C for use on other platforms. The generated code for those languages will use the exact same serialization and deserialization conventions as SwiftProtobuf, making it easy to exchange serialized data in binary or JSON forms, with no additional effort on your part.

Documentation

More information is available in the associated documentation:

  • Google's protobuf documentation provides 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 the protoc program
  • API.md documents how to use the generated code. This is recommended reading for anyone using SwiftProtobuf in their project.
  • INTERNALS.md documents the internal structure of the generated code and the library. This should only be needed by folks interested in working on SwiftProtobuf itself.
  • STYLE_GUIDELINES.md documents the style guidelines we have adopted in our codebase if you are interested in contributing

Getting Started

If you've worked with Protocol Buffers before, adding Swift support is very simple: you just need to build the protoc-gen-swift program and copy it into your PATH. The protoc program will find and use it automatically, allowing you to build Swift sources for your proto files. You will also, of course, need to add the SwiftProtobuf runtime library to your project as explained below.

System Requirements

To use Swift with Protocol buffers, you'll need:

  • A Swift 5.8 or later compiler (or, if building with Xcode, Xcode 14.3 or later as required by the App Store). The Swift protobuf project is being developed and tested against the latest release version of Swift available from Swift.org

  • Google's protoc compiler. The Swift protoc plugin is being actively developed and tested against the latest protobuf sources. The SwiftProtobuf tests need a version of protoc which supports the swift_prefix option (introduced in protoc 3.2.0). It may work with earlier versions of protoc. You can get recent versions from Google's github repository.

Building and Installing the Code Generator Plugin

To translate .proto files into Swift, you will need both Google's protoc 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.git
cd swift-protobuf

Pick what released version of SwiftProtobuf you are going to use. You can get a list of tags with:

git tag -l

Once you pick the version you will use, set your local state to match, and build the protoc plugin:

git checkout tags/[tag_name]
swift build -c release

This will create a binary called protoc-gen-swift in the .build/release directory.

To install, just copy this one executable into a directory that is part of your PATH environment variable.

NOTE: The Swift runtime support is now included with macOS. If you are using old Xcode versions or are on older system versions, you might need to use also use --static-swift-stdlib with swift build.

Alternatively install via Homebrew

If you prefer using Homebrew:

brew install swift-protobuf

This will install protoc compiler and Swift code generator plugin.

Converting .proto files into Swift

To generate Swift output for your .proto files, you run the protoc command as usual, using the --swift_out=<directory> option:

protoc --swift_out=. my.proto

The protoc program will automatically look for protoc-gen-swift in your PATH 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 using protoc-gen-swift can be found in the detailed Plugin documentation.

Adding the SwiftProtobuf library to your project...

To use the generated code, you need to include the SwiftProtobuf library module in your project. How you do this will vary depending on how you're building your project. Note that in all cases, we strongly recommend that you use the version of the SwiftProtobuf library that corresponds to the version of protoc-gen-swift you used to generate the code.

...using swift build

After copying the .pb.swift files into your project, you will need to add the SwiftProtobuf library to your project to support the generated code. If you are using the Swift Package Manager, add a dependency to your Package.swift file and import the SwiftProtobuf library into the desired targets. Adjust the "1.27.0" here to match the [tag_name] you used to build the 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")]
    ),
]

...using Xcode

If you are using Xcode, then you should:

  • Add the .pb.swift source files generated from your protos directly to your project
  • Add this SwiftPM package as dependency of your xcode project: Apple Docs

...using CocoaPods

If you're using CocoaPods, add this to your Podfile adjusting the :tag to match the [tag_name] you used to build the plugin above:

pod 'SwiftProtobuf', '~> 1.0'

And run pod install.

NOTE: CocoaPods 1.7 or newer is required.

Quick Start

Once you have installed the code generator, used it to generate Swift code from your .proto file, and added the SwiftProtobuf library to your project, you can just use the generated types as you would any other Swift struct.

For example, you might start with the following very simple proto file:

syntax = "proto3";

message BookInfo {
   int64 id = 1;
   string title = 2;
   string author = 3;
}

Then generate Swift code using:

protoc --swift_out=. DataModel.proto

The generated code will expose a Swift property for each of the proto fields as well as a selection of serialization and deserialization capabilities:

// Create a BookInfo object and populate it:
var info = BookInfo()
info.id = 1734
info.title = "Really Interesting Book"
info.author = "Jane Smith"

// As above, but generating a read-only value:
let info2 = 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`
let binaryData: Data = try info.serializedBytes()
// Resolve the `SwiftProtobufContiguousBytes` return value to `[UInt8]`
let binaryDataAsBytes: [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`
let decodedInfo = try BookInfo(serializedData: binaryData)

// Deserialize a received [UInt8] object from `binaryDataAsBytes`
let decodedInfo = try BookInfo(serializedBytes: binaryDataAsBytes)

// Serialize to JSON format as a Data object, or as any other type conforming to
// SwiftProtobufContiguousBytes. For example:
let jsonData: Data = try info.jsonUTF8Data()
let jsonBytes: [UInt8] = try info.jsonUTF8Bytes()

// Deserialize from JSON format from `jsonBytes`
let receivedFromJSON = try BookInfo(jsonUTF8Bytes: jsonBytes)

You can find more information in the detailed API Documentation.

Report any issues

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 the latest commit ID)
  • Any local changes you may have