SwiftFlatBuffers 1.2.2

SwiftFlatBuffers 1.2.2

测试已测试
语言语言 SwiftSwift
许可证 Apache-2.0
发布时间最后发布2018年5月
SPM支持 SPM

TonyStark106 维护。



  • 作者:
  • TonyStark106

简介

FlatBuffers 是一个高效的跨平台序列化库,适用于游戏和其他内存受限的应用程序。它允许您直接访问序列化数据,而无需首先解包/解析它,同时仍然具有出色的前后兼容性。

SwiftFlatBuffers 是 FlatBuffers 的 Swift 库,它通过友好界面支持了 FlatBuffers 的大多数功能。《1.1.0》版本开始兼容 Linux、Carthage 和 Swift 包管理器。

用法

生成源代码

构建 flatc

打开 SwiftFlatBuffers.xcworkspace 并将活动模式设置为 flatc,然后运行。在名为 flatc 的文件夹中找到二进制文件 flatc

编写一个模式

模式语法

// example schema
attribute "priority";

enum Color:byte (bit_flags) { Red = 0, Green, Blue = 3 }

union Any { Monster, Stat }

struct Vec3 (force_align: 16) {
  x:float;
  y:float;
  z:float;
  test1:double;
  test2:Color;
}

struct Ability {
  id:uint(key);
  distance:uint;
}

table Stat {
  id:string;
  val:long;
  count:ushort;
}

table Monster {
  pos:Vec3 (id: 0);
  hp:short = 100 (id: 2);
  mana:short = 150 (id: 1);
  name:string (id: 3, required, key);
  color:Color = Blue (id: 6);
  inventory:[ubyte] (id: 5);
  friendly:bool = false (deprecated, priority: 1, id: 4);
  testarrayoftables:[Stat] (id: 7);
  testarrayofstring:[string] (id: 8);
  testarrayofbools:[bool] (id: 9);
  testarrayofsortedstruct:[Ability] (id: 10);
  test:Any (id: 12);
}

root_type Monster;

生成

包含命名空间

./flatc -sw xxx.fbs

使用命名空间

./flatc -sw xxx.fbs --sw-namespace

安装

CocoaPods

pod "SwiftFlatBuffers"

Carthage

github "TonyStark106/SwiftFlatBuffers" ~> 1.2.2

Swift 包管理器

.Package(url: "https://github.com/TonyStark106/SwiftFlatBuffers.git", majorVersion: 1)

代码

import SwiftFlatBuffers

// Serialize
let m = Monster()
m.name = "Tony"
m.hp = 255
m.testarrayofstring = ["Spitfire", "coding"]
let data = m.toFBData()

// Deserialize
if let n = Monster(root: data) {
  print("Monster name:    \(n.name!)")
  print("Monster hp:      \(n.hp)")
  print("Monster skills:  \(n.testarrayofstring!)")
}

示例

  1. 编写您的模式文件并保存到 fbs 文件夹。
  2. 运行 sh build_flatbuffers.sh 将自动生成您的源代码并在 MyFlatBuffers.framework 中进行构建。
  3. 在示例项目中添加 import MyFlatBuffers 并尝试您的生成源代码。

单元测试

打开 SwiftFlatBuffers.xcworkspace 并将活动模式设置为 Example,然后按 Command + U

ExampleTests.swift

授权

SwiftFlatBuffers 使用 Apache License, Version 2.0 授权。请参阅 LICENSE 以获取完整授权文本。