FlatBuffers
An open source project by FPL.
|
Before diving into the FlatBuffers usage in Swift, it should be noted that the Tutorial page has a complete guide to general FlatBuffers usage in all of the supported languages (including Swift). This page is designed to cover the nuances of FlatBuffers usage, specific to Swift.
You should also have read the Building documentation to build flatc
and should be familiar with Using the schema compiler and Writing a schema.
The code for the FlatBuffers Swift library can be found at flatbuffers/swift
. You can browse the library code on the FlatBuffers GitHub page.
The code to test the Swift library can be found at flatbuffers/Flatbuffers.Test.Swift
. The test code itself is located in Flatbuffers.Test.Swift.
To run the tests, use the SwiftTest.sh shell script.
Note: The shell script requires Swift to be installed.
Note: See Tutorial for a more in-depth example of how to use FlatBuffers in Swift.
FlatBuffers supports reading and writing binary FlatBuffers in Swift.
To use FlatBuffers in your own code, first generate Swift structs from your schema with the --swift
option to flatc
. Then include FlatBuffers using SPM
in by adding the path to FlatBuffers/swift
into it. The generated code should also be added to xcode or the path of the package you will be using. Note: sometimes xcode cant and wont see the generated files, so it's better that you copy them to xcode.
For example, here is how you would read a FlatBuffer binary file in Swift: First, include the library and copy thegenerated code. Then read a FlatBuffer binary file or a data object from the server, which you can pass into the GetRootAsMonster
function.
Now you can access values like this:
In some cases it's necessary to modify values in an existing FlatBuffer in place (without creating a copy). For this reason, scalar fields of a Flatbuffer table or struct can be mutated.
The term mutate
is used instead of set
to indicate that this is a special use case. All mutate functions return a boolean value which is false if the field we're trying to mutate is not available in the buffer.