这边文章我们来简单分析一下DataModel.proto语法,聪明的你,一看就会明白:
syntax = "proto3"; // 申明语法proto3;如果没有这一句,默认是proto2语法;google推荐使用proto3
// proto支持注释,这就是注释语句
// message代表申明的模型,对应swift的struct,多个message将在同一个swift文件里面
message BookInfo {
int64 id = 1; // int64 对应swift Int64
string title = 2; // string 对应swift String
string author = 3;
}
message MyLibrary {
int64 id = 1;
string name = 2;
repeated BookInfo books = 3; // repeated代表books是个数组,里面包含的是BookInfo struct模型
map<string,string> keys = 4; // map<string,string>对应swift中的Dictionary<String,String>
}
特别需要注意的是:** swift生成的模型是struct,而struct在swift中是值类型,不是引用类型**;
proto还支持枚举类型(良心啊):
message SearchRequest {
enum Corpus { // 枚举类型
UNIVERSAL = 0; // 枚举的第一个值,必须为0,默认值
WEB = 1;
IMAGES = 2;
LOCAL = 3;
NEWS = 4;
PRODUCTS = 5;
VIDEO = 6;
}
Corpus corpus = 4;
}
类型与默认值
proto类型 | swift类型 | swift默认值 |
---|---|---|
string | String | "" |
int64 | Int64 | 0 |
bytes | Data | Data() |
bool | Bool | false |
repeated | 数组 | [], 即空数组 |
枚举 | enum | 枚举中的第一个值,且值必须为0 |
map | Dictionary | [:],即空字典 |
编译指令
最后来聊聊编译指令:
protoc --swift_out=. Test1.proto
// 原型为
protoc --swift_out=DST_DIR path/to/file.proto
因为我们要生成swift,所有用swift_out,如果要生成java,则用java_out,以此类推;
DST_DIR为生成代码的文件夹;
path/to/file.proto 为proto源文件路径;