Strings
In Flax, a string is a simply a series of characters, for example "Foo"
, "Поссия"
, and
"🐰🐼"
are all strings. Programmatically, they are represented by the String
type, which
is a part of the Foundation
library.
Flax Strings are UTF-8 aware, and is able to distinguish between the number of characters versus the number of
bytes. The subunit of String
, the Character
class, is basically a minified string, holding
zero or more bytes, defining a UTF-8 codepoint.
Despite this, Flax Strings still allow arbitrary indexing via the subscript operator, although the operation happens i
O(n)
time due to the nature of UTF-8.
As with the rest of Flax, the String
type is designed to interoperate as seamlessly as possible with C;
String
s can be transparently converted to Int8*
, which is equivalent to const char*
in C.
This is simply an access on the first member of the struct, so care must be taken passing it to mutating functions.
Basic Strings
String Literals
The most straightforward way to use strings in Flax is through a string literal, which is simply a series of characters enclosed in double quotes. String literals can contain Unicode characters, but the source file should be saved as UTF-8 to allow compatibility.
"This is a string."
String literals can be assigned to variables, passed to functions, or otherwise used like a normal expression.
var str = "This is a string."
str = "You've changed." // this is legal
However, they are immutable, so they cannot be the target of an assignment.
"haha no." = "lol what" // error
Mutability
The string is a regular type like anything else, so the mutability of a String
variable depends on whether
it was defined with let/val
or var
.
let str = "Modify me!"
str += "another!" // error
Value Behaviour
Flax strings are value-types, meaning that expressions taking a string are given a copy of the original, such that modifying the new string has no effect on the original string.
var string1 = "String One"
var string2 = string1 // the contents of string1 are copied
string2 += "???"
println(string1) // prints "String One"
println(string2) // prints "String One???"
The exception is where both the recipient and source of the string are immutable, in which case no copy is made, since
it is unnecessary.
let string1 = "String One"
let string2 = string1 // no copy
Characters
Flax allows you to index into a String
to get at the characters that make it up. Due to the nature of UTF-8,
a Character
is actually a series of bytes that come together to represent a Unicode codepoint.
There's really no point in having a separate syntax for characters, so in fact characters are simply initialised using string
literals. Thus, an explicit type must be specified, to prevent the variable from being inferred as type String
.
let char: Character = "π"