String Concatenation and Interpolation

String in Swift

Tested on: Xcode 12.2, Swift 5.3

A string is a collection of characters. For example, the word "Wes" contains the follow characters "W", "e", "s". In fact, all the chacters are numbers. When you key a character on your keyboard, you are communicating the number of the chacter to the computer and the computer process the number and convert it into a characters. For example,Unicode, "a" contains a number 97. In this reference, you won't be learning about unicode but you will be learning the core concept of String in iOS application or Swift.

  1. How to create String?
  2. Multiline string
  3. String Concatenation
  4. String Interpolation





1. How to create String?

In Swift and other programming languages such as Kotlin or Python, you can work with characters and strings directly. To create string, you use double quotation marks like the one shown below. The constant myName is assigned to "Wes" which stored multiple characters.

Swift Code :

let myName = "Wes"

You can also declare the date type. However, because of the advantage of Swift's type interfering. You do not need to do so as shown above.

Swift Code :

let myName : String = "Wes"

Character

If you are wondering about creating character in Swift, you use double quotation marks. But you have to state the data type (character) because Swift will think that it is a string instead of a character.

Swift Code :

let aCharacter : Character = "W"



2. Multiline string

The multiline string can be created using triple quotation marks. This is useful when you want to store a very long string in your code.

Swift Code :

let multi = " This
    is
    a
    multiline
    string
    "



3. String Concatenation

Sometimes you might need to combine two or more string together. In most programming languages, combine two or more string is called String Concatenation. Swift provide a simple way of doing so. As shown below, string concatenation will not add any spaces for you.

Swift Code :

let multi = "Hallo"
print(multi + "Wes")

Output :

HalloWes

Remember string concatenation only works when combining String and String. You cannot caoncatenate String and Int or other data type together. In order to do that, you have to change the datatype of Int to string using Type Conversion.

Swift Code :

let age = 2
print("My age is " + String(age))

Output :

My age is 2




4. String Interpolation

String interpolation is another way of combine String and String or other datatypes together. The syntax is much more readable than the one shown in string concatenation above. This special Swift syntax allows you to build a string from other data types such as integer as shown below:

Swift Code :

let age = 2
print("My age is \(age)")

Output :

My age is 2