Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Google ProtocolBuffers for Apple Swift

License

NotificationsYou must be signed in to change notification settings

lcoderre/protobuf-swift

 
 

Repository files navigation

#Protocol Buffers for Swift

Build StatusCarthage compatibleVersionPlatform

An implementation of Protocol Buffers in Swift.

Protocol Buffers are a way of encoding structured data in an efficient yet extensible format. This project is based on an implementation of Protocol Buffers from Google. See theGoogle protobuf project for more information.

####Required Protocol Buffers 2.6

##How To Install Protobuf Compiler from Homebrew

1.ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

2.brew install protobuf-swift

##How To Install Protobuf Compiler

1.ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

2.brew install automake

3.brew install libtool

4.brew install protobuf

5.git clone git@github.com:alexeyxo/protobuf-swift.git

6../scripts/build.sh

Add./src/ProtocolBuffers/ProtocolBuffers.xcodeproj in your project.

##Cocoapods

Podfile:

use_frameworks!pod 'ProtocolBuffers-Swift'

## Installation viaCarthage

Cartfile:

github "alexeyxo/protobuf-swift"

##Compile ".proto" files.

protoc  person.proto --swift_out="./"

##Serializing

syntax="proto2";messagePerson {requiredint32id=1;requiredstringname=2;optionalstringemail=3;}
letpersonBuilder=Person.Builder()personBuilder.id=123personBuilder.name="Bob"personBuilder.email="bob@example.com"letperson= personBuilder.build()println("\(person)")person.data() //return NSData

##Chaining

syntax="proto2";messagePerfomance{requiredint32ints=1;requiredint64ints64=2;requireddoubledoubles=3;requiredfloatfloats=4;optionalstringstr=5;optionalbytesbytes=6;optionalstringdescription=7;}
varoriginalBuilder=ProtoPerfomance.Builder()originalBuilder.setInts(Int32(32)).setInts64(Int64(64)).setDoubles(Double(12.12)).setFloats(Float(123.123)).setStr("string")letoriginal= originalBuilder.build()

##Sub Builders

syntax="proto2";messageFoo {optionalint32val=1;// some other fields.}messageBar {optionalFoofoo=1;// some other fields.}messageBaz {optionalBarbar=1;// some other fields.}
varbuilder= baz.toBuilder()builder.getBarBuilder().getFooBuilder().setVal(10)baz= builder.build()

##Maps(ProtocolBuffers 3.0)

syntax="proto3";messageMapMessageValue{int32valueInMapMessage=1;}messageMessageContainsMap{enumEnumMapValue  {FirstValueEnum=0;SecondValueEnum=1;  }map<int32,int32>map_int32_int32=1;map<int64,int64>map_int64_int64=2;map<string,string>map_string_string=3;map<string,bytes>map_string_bytes=4;map<string,MapMessageValue>map_string_message=5;map<int32,EnumMapValue>map_int32_enum=6;}
finalinternalclassMessageContainsMap:GeneratedMessage,GeneratedMessageProtocol,Hashable{...private(set)varmapInt32Int32:Dictionary<Int32,Int32>=Dictionary<Int32,Int32>()private(set)varmapInt64Int64:Dictionary<Int64,Int64>=Dictionary<Int64,Int64>()private(set)varmapStringString:Dictionary<String,String>=Dictionary<String,String>()private(set)varmapStringBytes:Dictionary<String,NSData>=Dictionary<String,NSData>()private(set)varmapInt32Enum:Dictionary<Int32,MessageContainsMap.EnumMapValue>=Dictionary<Int32,MessageContainsMap.EnumMapValue>()...}

##Deserializing

varperson=Person.parseFromData(bytes) // from NSData

##Using Oneof

syntax="proto3";messageSubMessage {stringstr=1;}messageSampleMessage {oneoftest_oneof {stringname=4;int32id=5;SubMessagemes=6;  }}
varsm=SampleMessage.Builder()sm.name="Alex"sm.id=123println(ss.build()) //->  id: 123

##Nested Types

syntax="proto3";messageSearchResponse {messageResult {stringurl=1;stringtitle=2;repeatedstringsnippets=3;    }repeatedResultresult=1;}
varbuilderResult=SearchResponse.Result.Builder()builderResult.url="http://protobuf.axo.io"builderResult.title="Protocol Bufers Apple Swift"varsearchRespons=SearchResponse.builder()searchRespons.result+=[builderResult.build()]println(searchRespons.build())

##Packages

syntax="proto2";packageFooBar;messagePerfomance{requiredint32ints=1;requiredint64ints64=2;requireddoubledoubles=3;requiredfloatfloats=4;optionalstringstr=5;optionalbytesbytes=6;optionalstringdescription=7;}
publicextensionFooBar{...finalpublicclassPerfomance:GeneratedMessage,GeneratedMessageProtocol{...}}

##Custom Options

enumAccessControl {InternalEntities=0;PublicEntities=1;}messageSwiftFileOptions {optionalstringclass_prefix=1;optionalAccessControlentities_access_control=2 [default =InternalEntities];optionalboolcompile_for_framework=3 [default =true];}

At now protobuf-swift's compiler is supporting three custom options(file options).

  1. Class Prefix
  2. Access Control
  3. Compile for framework

If you have use custom options, you need to add:

import 'google/protobuf/swift-descriptor.proto';

in your.proto files.

###Class prefix

This option needs to generate class names with prefix.

Example:

import 'google/protobuf/swift-descriptor.proto';option (.google.protobuf.swift_file_options).class_prefix = "Proto";messageNameWithPrefix{optionalstringstr=1;}

Generated class has a name:

finalinternalclass ProtoNameWithPrefix: GeneratedMessage

###Access control

option (.google.protobuf.swift_file_options).entities_access_control = PublicEntities;

All generated classes marks asinternal by default. If you want mark aspublic, you can useentities_access_control option.

option (.google.protobuf.swift_file_options).entities_access_control = PublicEntities;messageMessageWithCustomOption{optionalstringstr=1;}

Generated class and all fields are marked apublic:

finalpublicclass MessageWithCustomOption: GeneratedMessage

###Compile for framework

option (.google.protobuf.swift_file_options).compile_for_framework = false;

This option deletes the stringimport ProtocolBuffers of the generated files.

####If you will need some other options, write me. I will add them.

##Utilities (ProtocolBuffers 3.0)

Added well-known type protos (any.proto, empty.proto, timestamp.proto, duration.proto, etc.). Users can import and use these protos just like regular proto files. Addtional runtime support will be added for them in future releases (in the form of utility helper functions, or having them replaced by language specific types in generated code).####Any

messageAny {// A URL/resource name whose content describes the type of the// serialized message.//// For URLs which use the schema `http`, `https`, or no schema, the// following restrictions and interpretations apply://// * If no schema is provided, `https` is assumed.// * The last segment of the URL's path must represent the fully//   qualified name of the type (as in `path/google.protobuf.Duration`).// * An HTTP GET on the URL must yield a [google.protobuf.Type][google.protobuf.Type]//   value in binary format, or produce an error.// * Applications are allowed to cache lookup results based on the//   URL, or have them precompiled into a binary to avoid any//   lookup. Therefore, binary compatibility needs to be preserved//   on changes to types. (Use versioned type names to manage//   breaking changes.)//// Schemas other than `http`, `https` (or the empty schema) might be// used with implementation specific semantics.//// Types originating from the `google.*` package// namespace should use `type.googleapis.com/full.type.name` (without// schema and path). A type service will eventually become available which// serves those URLs (projected Q2/15).stringtype_url=1;// Must be valid serialized data of the above specified type.bytesvalue=2;}
Google.Protobuf.Any()

####API

messageApi {// The fully qualified name of this api, including package name// followed by the api's simple name.stringname=1;// The methods of this api, in unspecified order.repeatedMethodmethods=2;// Any metadata attached to the API.repeatedOptionoptions=3;// A version string for this api. If specified, must have the form// `major-version.minor-version`, as in `1.10`. If the minor version// is omitted, it defaults to zero. If the entire version field is// empty, the major version is derived from the package name, as// outlined below. If the field is not empty, the version in the// package name will be verified to be consistent with what is// provided here.//// The versioning schema uses [semantic// versioning](http://semver.org) where the major version number// indicates a breaking change and the minor version an additive,// non-breaking change. Both version numbers are signals to users// what to expect from different versions, and should be carefully// chosen based on the product plan.//// The major version is also reflected in the package name of the// API, which must end in `v<major-version>`, as in// `google.feature.v1`. For major versions 0 and 1, the suffix can// be omitted. Zero major versions must only be used for// experimental, none-GA apis.//// See also: [design doc](http://go/api-versioning).////stringversion=4;// Source context for the protocol buffer service represented by this// message.SourceContextsource_context=5;}// Method represents a method of an api.messageMethod {// The simple name of this method.stringname=1;// A URL of the input message type.stringrequest_type_url=2;// If true, the request is streamed.boolrequest_streaming=3;// The URL of the output message type.stringresponse_type_url=4;// If true, the response is streamed.boolresponse_streaming=5;// Any metadata attached to the method.repeatedOptionoptions=6;}
Google.Protobuf.Api()

####Duration

messageDuration {// Signed seconds of the span of time. Must be from -315,576,000,000// to +315,576,000,000 inclusive.int64seconds=1;// Signed fractions of a second at nanosecond resolution of the span// of time. Durations less than one second are represented with a 0// `seconds` field and a positive or negative `nanos` field. For durations// of one second or more, a non-zero value for the `nanos` field must be// of the same sign as the `seconds` field. Must be from -999,999,999// to +999,999,999 inclusive.int32nanos=2;}
Google.Protobuf.Duration()

####Empty

messageEmpty {}
Google.Protobuf.Empty()

####Field Mask

messageFieldMask {// The set of field mask paths.repeatedstringpaths=1;}
Google.Protobuf.FieldMask()

####Source context

messageSourceContext {// The path-qualified name of the .proto file that contained the associated// protobuf element.  For example: `"google/protobuf/source.proto"`.stringfile_name=1;}
Google.Protobuf.SourceContext()

####Struct

messageStruct {// Map of dynamically typed values.map<string,Value>fields=1;}// `Value` represents a dynamically typed value which can be either// null, a number, a string, a boolean, a recursive struct value, or a// list of values. A producer of value is expected to set one of that// variants, absence of any variant indicates an error.messageValue {oneofkind {// Represents a null value.NullValuenull_value=1;// Represents a double value.doublenumber_value=2;// Represents a string value.stringstring_value=3;// Represents a boolean value.boolbool_value=4;// Represents a structured value.Structstruct_value=5;// Represents a repeated `Value`.ListValuelist_value=6;  }}// `ListValue` is a wrapper around a repeated field of values.messageListValue {// Repeated field of dynamically typed values.repeatedValuevalues=1;}// `NullValue` is a singleton enumeration to represent the null// value for the `Value` type union.enumNullValue {// Null value.NULL_VALUE=0;}
Google.Protobuf.Struct()

####Timestamp

messageTimestamp {// Represents seconds of UTC time since Unix epoch// 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to// 9999-12-31T23:59:59Z inclusive.int64seconds=1;// Non-negative fractions of a second at nanosecond resolution. Negative// second values with fractions must still have non-negative nanos values// that count forward in time. Must be from 0 to 999,999,999// inclusive.int32nanos=2;}
Google.Protobuf.Timestamp()

####Type

messageType {// The fully qualified message name.stringname=1;// The list of fields.repeatedFieldfields=2;// The list of oneof definitions.// The list of oneofs declared in this Typerepeatedstringoneofs=3;// The proto options.repeatedOptionoptions=4;// The source context.SourceContextsource_context=5;}// Field represents a single field of a message type.messageField {// Kind represents a basic field type.enumKind {// Field type unknown.TYPE_UNKNOWN=0;// Field type double.TYPE_DOUBLE=1;// Field type float.TYPE_FLOAT=2;// Field type int64.TYPE_INT64=3;// Field type uint64.TYPE_UINT64=4;// Field type int32.TYPE_INT32=5;// Field type fixed64.TYPE_FIXED64=6;// Field type fixed32.TYPE_FIXED32=7;// Field type bool.TYPE_BOOL=8;// Field type string.TYPE_STRING=9;// Field type message.TYPE_MESSAGE=11;// Field type bytes.TYPE_BYTES=12;// Field type uint32.TYPE_UINT32=13;// Field type enum.TYPE_ENUM=14;// Field type sfixed32.TYPE_SFIXED32=15;// Field type sfixed64.TYPE_SFIXED64=16;// Field type sint32.TYPE_SINT32=17;// Field type sint64.TYPE_SINT64=18;  }// Cardinality represents whether a field is optional, required, or// repeated.enumCardinality {// The field cardinality is unknown. Typically an error condition.CARDINALITY_UNKNOWN=0;// For optional fields.CARDINALITY_OPTIONAL=1;// For required fields. Not used for proto3.CARDINALITY_REQUIRED=2;// For repeated fields.CARDINALITY_REPEATED=3;  }// The field kind.Kindkind=1;// The field cardinality, i.e. optional/required/repeated.Cardinalitycardinality=2;// The proto field number.int32number=3;// The field name.stringname=4;// The type URL (without the scheme) when the type is MESSAGE or ENUM,// such as `type.googleapis.com/google.protobuf.Empty`.stringtype_url=6;// Index in Type.oneofs. Starts at 1. Zero means no oneof mapping.int32oneof_index=7;// Whether to use alternative packed wire representation.boolpacked=8;// The proto options.repeatedOptionoptions=9;}// Enum type definition.messageEnum {// Enum type name.stringname=1;// Enum value definitions.repeatedEnumValueenumvalue=2;// Proto options for the enum type.repeatedOptionoptions=3;// The source context.SourceContextsource_context=4;}// Enum value definition.messageEnumValue {// Enum value name.stringname=1;// Enum value number.int32number=2;// Proto options for the enum value.repeatedOptionoptions=3;}// Proto option attached to messages/fields/enums etc.messageOption {// Proto option name.stringname=1;// Proto option value.Anyvalue=2;}
Google.Protobuf.Type()...

####Wrappers

// Wrapper message for double.messageDoubleValue {// The double value.doublevalue=1;}// Wrapper message for float.messageFloatValue {// The float value.floatvalue=1;}// Wrapper message for int64.messageInt64Value {// The int64 value.int64value=1;}// Wrapper message for uint64.messageUInt64Value {// The uint64 value.uint64value=1;}// Wrapper message for int32.messageInt32Value {// The int32 value.int32value=1;}// Wrapper message for uint32.messageUInt32Value {// The uint32 value.uint32value=1;}// Wrapper message for bool.messageBoolValue {// The bool value.boolvalue=1;}// Wrapper message for string.messageStringValue {// The string value.stringvalue=1;}// Wrapper message for bytes.messageBytesValue {// The bytes value.bytesvalue=1;}
Google.Protobuf.StringValue()

Credits

Developer - Alexey Khokhlov

Google Protocol Buffers - Cyrus Najmabadi, Sergey Martynov, Kenton Varda, Sanjay Ghemawat, Jeff Dean, and others

About

Google ProtocolBuffers for Apple Swift

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift92.5%
  • Protocol Buffer4.7%
  • C++2.8%
  • Ruby0.0%
  • Shell0.0%
  • M40.0%

[8]ページ先頭

©2009-2025 Movatter.jp