In Swift, you can handle vectors, matrices, and quaternions, using the standard library SIMD vector types and the Accelerate simd library. They are related as shown in the figure below.
This cheat sheet shows an overview and sample code for each type.
- download
Swift SIMD Type Cheat Sheat
: PDF
The SIMD Vector Types were added in Swift 5 Standard Library.
They consist of SIMD2<Scalar>, SIMD3<Scalar>, SIMD4<Scalar>, SIMD8<Scalar>, SIMD16<Scalar>, SIMD32<Scalar>
, and SIMD64<Scalar>
.
The Scalar
is a type conforming to the SIMDScalar
protocol,
such as Double, Float, Float16, Int, Int8, Int16, Int32, Int64, UInt, UInt8, UInt16, UInt32
, and UInt64
.
The SIMD
protocol defines properties, methods, and operators
for SIMD vectors.
The cheat sheet shows the definition of each type and protocol, as well as sample code.
Sample Code:
- Swift Playground Code Gist
References:
- Apple Documentation SIMD Vector Types
- Swift-evolution SE-0229 SIMD Vectors
It provides Signed Integer Vectors, Unsigned Integer Vectors, and Floating-Point Vectors. Since simd types are typealias of Standard Library SIMD types, you can take advantage of SIMD type functions.
The cheat sheet shows the types and functions which can be used on the types, as well as sample code.
Sample Code:
- Swift Playground Gist
References:
- Apple Documentation, Accelerate simd
- Apple Documentation, Article Working with Vectors
- Apple WWDC18 Video Using Accelerate and simd
It provides Single-Precision Floating-Point Matrices and Double-Precision Floating-Point Matrices. The Matrices are up to 4 columns x 4 rows. (column major naming convention)
The cheat sheet shows the types and functions which can be used on the types, as well as sample code.
Sample Code:
- Swift Playground Gist
References:
- Apple Documentation, Article Working with Matrices
It provides Single-Precision Quaternion Type simd_quatf
and Double-Precision Quaternion Type simd_quatd
.
Quaternions
- Quaternions are defined by a scalar (real) part, and three imaginary parts collectively called the vector part. Quaternions are often used in graphics programming as a compact representation of the rotation of an object in three dimensions.
- The length of a quaternion is the square root of the sum of the squares of its components.
- Quaternions rotate points around the surface of a sphere, and interpolate between them.
- Quaternions have some advantages over matrices. For example, they're smaller: A 3 x 3 matrix of floats is 48 bytes, and a single-precision quaternion is 16 bytes. They also can offer better performance: Although a single rotation using a quaternion is a little slower than one using a matrix, when combining actions, quaternions can be up to 30% faster.
Sample Code:
- Swift Playground Gist
References:
- Apple Documentation, Article Working with Quaternions
- Apple Sample Code Rotating a Cube by Transforming Its Vertices
License: CC0