Why and when to use the Swift's StaticString struct

Subscribe to my newsletter and never miss my upcoming articles

Hello brothers and sisters, Leo here.

Today we'll look to a struct in Swift called StaticString.

Let's code!

The problem

You need to assert that a string will be complete in compile time, complete means you won't do any string interpolation inside it.

Declaring a string can be done easily like:

let test = "My name is"
print(test)

With the String class you can add information to that string in runtime, with string interpolation. See below the example:

var myNumber = 10
let myString = "My number is \(myNumber)"

print(myString)
myNumber = 20
print(myString)

And the result is:

Screen Shot 2020-09-08 at 10.54.36.png

You can see, even if you change de var myNumber, the text myString won't change. The string interpolation only takes in consideration the value in the moment you are assigning the value, this way even changing the value in the future the string will be the same.

But using string interpolation you can't guarantee in compile time what the value of that string. So to do that you can use StaticString struct to help you out.

The code below won't compile anymore.

var myNumber = 10
let myString : StaticString = "My number is \(myNumber)"

print(myString)

Screen Shot 2020-09-08 at 11.19.09.png

And you can't use any of the other string syntax-sugar as well like:

var myNumber = 10
let myString : StaticString = "My number is " + "\(myNumber)"

print(myString)

This way you can force the development to always have the full string in compile time.

You can't even add one StaticString to another:

let myString : StaticString = "My number is "
let myString2 : StaticString = "23"

myString2 = myString + myString2

Wrap-up

The use case for StaticString is when you want two things:

  1. You want to know the value of the string in compile time.
  2. You don't want to modify it's value in any way at any time.

I hope you enjoy the content like I did and if learned something new let me now! The feedbacks are always welcome.

Thanks for the reading and... That's all folks!

Credit: image

No Comments Yet