How to make Strings easier to Debug in Swift
Today we will make debugging Strings in Swift a joy instead of a nightmare. Have you ever gotten a reply from an API with an empty string? I am sure you have. Well with this code you can tell what is being set to the variable, and when your Strings are being set to empty strings (ex; ““). The code is simple, but useful. Below is the code snippet that does all the heavy lifting.
Now let me explain what the code above is doing. The DidSet method inside of our variable is called once your variable is set. There is also WillSet which we will not be using in this tutorial. However it can be useful as well depending on the functionality you want to implement. Inside of the DidSet we have an if else statement that does the following. In the if statement we check if the string is empty. If the string is empty we throw a compiler error which will stop the whole application. in the else statement we print out the variables current value when the variable is set. That is all the code does. Why is this useful? well imagine you are trying to get a String from an API you have to handle this exception when calling the variable this way you can place a message stating that the API returned nothing. or in the other case of our functionality you are setting a variable to a specific String, and the string returns the wrong string, well you can see this in the console. In the code snippet below we will show you how the variable looks if we simply set it to a value, and show you the output in the console.
See how easy it is to spot a set variable in the console? Well this will speed up the debugging process because you can simply see the flow of your variable as the code compiles. Now we will show you how our empty string functionality throws an exception. BE CAREFUL if you want to implement this part of the code because if you don’t handle this exception your whole application will crash.
Because you can’t use try cath with fatalError() you have to conditionally check if the variable is empty. This is not a common way of doing this, however it forces you to handle this state of your variable when otherwise your application would just crash like shown in the image below.