Swift - String value creation

Introduction

In Swift, a string literal is a sequence of characters enclosed by a pair of double quotes "".

The following code shows a string literal assigned to a constant and another to a variable:

let str1 = "This is a string in Swift"        //str1 is a constant
var str2 = "This is another string in Swift"  //str2 is a variable

Because the compiler uses type inference, there is no need to specify the type of constant and variable.

However, if you wish, you could still specify the String type explicitly:

var str3 :String  = "This is yet another string in Swift"

To assign an empty string to a variable, you can simply use a pair of empty double quotes, or call the initializer of the String type, like this:

var str4 = ""
var str5 = String ()

The preceding statements initialize both str4 and str5 to contain an empty string.

To check whether a variable contains an empty string, use the isEmpty() method of the String type:

if str4.isEmpty {
    print("Empty string")
}

Related Topic