Swift – Create String Variable

To create a String variable in Swift, declare the variable as String, or assign empty string to the variable, or assign new String instance to the variable.

In the following code snippet, we declare a variable name of type String.

</>
Copy
var name: String

In the following code snippet, we define a variable name and assign an empty string value.

</>
Copy
var name = ""

In the following code snippet, we define a variable name and assign a new instance of String.

</>
Copy
var name = String()

Let us now programmatically print the type of the variable to output, and check if the type of the variable is String or not.

First, we will start with the process of explicit declaration of the variable as String.

main.swift

</>
Copy
import Foundation

var name: String
print(type(of: name))

We used type(of:) generic function to get the data type of the variable.

Output

String

Now, assign empty string to the variable, and check if the type of the variable is String.

main.swift

</>
Copy
import Foundation

var name = ""
print(type(of: name))

Output

String

Now, we will check for new String assignment process.

main.swift

</>
Copy
import Foundation

var name = String()
print(type(of: name))

Output

String

In all the three cases, we have determined that the variable is of type String.

Conclusion

Conclusion this Swift Tutorial, we learned how to declare or create a String variable in Swift, in different ways, with the help of examples.