Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. —— Google Official Definitionjavascript
簡單地說,Protocol Buffers 就是一種輕量高效的結構化數據交換格式,語言無關、平臺無關、可擴展。理解地直白粗暴一點就是「更厲害更面向將來的 JSON」,那麼接下來咱們就將經過 Swift 官方實現的 Protobuf
來一探究竟。java
從去掉軟盤到幹掉光驅,從擯棄 Flash
推廣 HTML5
,到如今乾脆把標準音頻接口抹去,蘋果一貫善於引領科技時尚,那麼在面向將來的數據交換格式上天然不會落後,所以 Swift Protobuf
應運而生。linux
原本我想拿照官方示例來走一遍的,但此次正好有個絕佳的示例,既有客戶端又有服務端,能夠「作」享其成一次,其中還涉及到 Go
語言,趁此機會也能夠把玩一番。git
將 ProtoBufExample 克隆至本地github
➜ git clone https://github.com/KyoheiG3/ProtobufExample.git
➜ cd ProtobufExample複製代碼
配置客戶端golang
➜ cd ./ProtobufClient
➜ pod install複製代碼
初始化服務端shell
➜ cd ./ProtobufServer
➜ swift build
// 建立工程文件,以便在 Xcode 下編輯
➜ swift package generate-xcodeproj複製代碼
啓動 APIjson
➜ ./.build/debug/api複製代碼
配置並啓動服務 with Goswift
➜ go get github.com/golang/protobuf/protoc-gen-go
➜ go run server/api.go複製代碼
➜ mkdir ~/go
➜ export GOPATH=~/go
➜ export PATH=$PATH:$GOPATH/bin複製代碼
.proto
安裝
protobuf
api
➜ brew install protobuf複製代碼
用 Swift 編譯
protobuf
➜ cd ./ProtobufServer
➜ swift build
➜ protoc --plugin=protoc-gen-swift=.build/debug/protoc-gen-swift --swift_out=../protos --proto_path=../protos ../protos/DataModel.proto複製代碼
此時咱們就能在 protos
這個輸出目錄下就能夠看到剛剛生成的對應 .pb.swift
文件了。
/* * Generated by the protocol buffer compiler. * Source: DataModel.proto */
import Foundation
import SwiftProtobuf
public struct BookInfo: ProtobufGeneratedMessage {
public var swiftClassName: String {return "BookInfo"}
public var protoMessageName: String {return "BookInfo"}
public var protoPackageName: String {return ""}
public var jsonFieldNames: [String: Int] {return [
"id": 1,
"title": 3,
"author": 2,
]}
public var protoFieldNames: [String: Int] {return [
"id": 1,
"title": 3,
"author": 2,
]}
public var id: Int64 = 0
public var title: String = ""
public var author: String = ""
public init() {}
......
......
......
if !keys.isEmpty {
try visitor.visitMapField(fieldType: ProtobufMap<ProtobufString,ProtobufString>.self, value: keys, protoFieldNumber: 4, protoFieldName: "keys", jsonFieldName: "keys", swiftFieldName: "keys")
}
}
public func _protoc_generated_isEqualTo(other: MyLibrary) -> Bool {
if id != other.id {return false}
if name != other.name {return false}
if books != other.books {return false}
if keys != other.keys {return false}
return true
}
}複製代碼
其中還包括了一些對 JSON
的友好兼容,感興趣的朋友能夠本身動手玩一下。
ProtoBuf