Hello brothers and sisters, Leo here. Today we’ll look to a struct in Swift called StaticString.
It is always good to know what the native APIs can provide to us in terms of capabilities, optimizations, and intentions. StaticString is one of the things that make perfectly clear what are your intentions with your types. This way you can use the type system in your favor and express to others ( and possibly yourself in the future ) what your code should do.
The problem – How to use StaticString in Swift
You need to assert that a string will be complete in compile time, complete means you won’t do any string interpolation inside it. In other words, you should block String interpolation.
Declaring a string and printing in the console 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:
You can see, that even if you change de var myNumber, the text myString won’t change. The string interpolation only takes into consideration the value at 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 the value of that string. So to do that you can use the 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)
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 developers 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
The use case for StaticString is when you want two things:
- You want to know the value of the string in compile time.
- You don’t want to modify its value in any way at any time.
The StaticString is very useful in a very specific situation, and you probably won’t use that very often in your codebase. That said, when you have the necessity of compile-time safety when dealing with string, this is perfect.
That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to
freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.
Thanks for the reading and… That’s all folks.
Credits – image