4 ms·
So now Swift has the best strings :) Or at least will have, when these changes are released. > Single byte storage, so it works well with utf-8. Check, underl
by jchb 8y ago
So now Swift has the best strings :)
Or at least will have, when these changes are released.
> Single byte storage, so it works well with utf-8.
Check, underlying storage is a byte array with the utf-8 encoding.
> Byte length field, so it knows the length of every string and it can store null bytes.
Check.
> An additional null byte past the end and pointer shifting, so every Pascal string is also a C pchar string.
Check, getting a C string from a Swift string is O(1).
> Reference-counted copy-on-write, so you can copy it in constant time for reading and treat it as if the string was fully copied for writing.
Check.
> Low-level memory management, so it can store 2 GB long strings.
Check, just tested with a 4 GB string on macOS.
> And in most situations you do not need a string builder, because strings are freed immediately and very fast when the refcounts zeros without staying around as garbage.
Check, Swift objects are reference counted, storage of intermediary strings will be freed as soon as they go out of scope.
> Behaves as a value type with the null pointer being the empty string, so you can never get a null pointer exception.
Check, String is a value type.
> (Optionally) index checked with the length, so you can never get a buffer overflow.
Check, this is the default - trap on out-of-bounds access rather than an illegal memory access. If you really want can disable by compiling with -Ounchecked.
> Unfortunately the newer FreePascal/Delphi versions made it all very confusing by adding an encoding field. In the past you could just assume all strings are UTF-8 as code style rule
Check. String operations are performed on grapheme clusters (rather than for example UTF-8 code points), which is generally the right level of abstraction to work with. There are "views" for accessing specific encodings.