alphabet close up communication conceptual

Strings, Integers & Interpolation

In programming depending on what you are doing with text or numbers within SwiftUI, you will be using different types for different uses. These different types are Strings & Integers. So what’s the difference between them, where are they used and what are some examples of uses of each of these types. Let’s go though them.

Strings: 

A string in the very simplest terms is a group of characters. In most cases the easiest way to identify a string would be a sentence or any length of text. This is written in SwiftUI by using the Text Object:

Text(This is a line of simple text and it is a string”)

If you want to write any text in SwiftUi this is how it is done. But what about numbers, are they different? It depends on how your using them. If you are just wanting to have numbers in your code as simple text to read you could enter numbers this way as well, in fact any character written can be input using the Text object:

Text(“1234567890”)

This will simply display these numbers within the app. If you wanted to add numbers created as Strings this will not work as you would expect. If you tried to add numbers as strings they would present themselves as one added on to the end of the other rather than add up the numbers themselves because as far as SwiftUI is concerned anything that’s a String isn’t a number its simply a bunch of characters being displayed.

Text(“1”) + Text(“1”)

Makes

11 not 2

If you wanted to use the numbers by adding them etc.. the best way is to enter them as Integers.

Integers:

When working with numbers when being used to be used as numbers and not simply as a character within the app Integers are used. This can be done by creating a variable and simply making it equal a number. If you have multiple Integers these can then be used for addition, subtraction, multiplication etc… To display the numbers in an app they can be placed within a String by using something called Interpolation. This is done by writing \( ) within the quotes of a String and placing variables within the brackets and this will place the Integer within the string itself and then it can be displayed:

Text(“ \(1+2) ”)

Makes 

3

So as you can see we use Strings to display characters and Integers to use numbers that can be added, subtracted or multiplied. But these can be used together to show them all together by using interpolation:

Text(“One plus three equals: \(1+2) ”)

Makes

One plus three equals: 3

Play around with these and get familiar with using these in different combinations, no limit as to what you can create.

Leave a Comment

Your email address will not be published. Required fields are marked *