How To Use Swift String Example

String is a very useful data type in programming language especially in swift. This article will show you some examples about how to create string, manipulate string in swift coding. To make the code execution immediately to show the result, you had better create a xcode playground project and run below example code in it, you can read article How To Use Xcode Playground Project Example to learn more about xcode playground.

1. Create String Type Variable.

String class is used to declare a string type variable, so you can declare a string variable use var str:String = "", for simplicity, you can ignore the String class when the initialize value is a string such as var str = "hello". You can also declare a string variable use String class constructor var str = String() and then assign string text value to it.

Please note in swift the variable should has an initial value before use it, otherwise if you use a none initialized variable, xcode will throw an error like error: variable ‘str’ used before being initialized.

  1. Below code will create a string type variable, the string content can be any language text.
    var str = "hello swift, 你好"

    Below is the execution result.

    hello swift, 你好
  2. String variable is also a character array, so you can loop in the string and print out each character.
    // declare a swift string variable.
    var str:String = String()
    str = "hello swift, 你好"
    // loop in the string array.
    for cha in str{
        // print out each character.

    Below is the execution result.


2. Concat String & Other Data Type Variable Value.

  1. Concat two string variable with + operator.
    var str1 = "hello"
    var str2 = "Jerry"
    var str3 = str1 + " " + str2

    Above code will get below result.

    hello Jerry

    But if the string variable is a constant variable, then you can not change it’s value.

    var str1 = "hello"
    let str2 = "Jerry"
    // this line of code will throw error Cannot assign to value: 'str2' is a 'let' constant
    str2 = str2 + " " + str1 
  2. Concat string with other data type variable. You can insert any type variable value in a string use \(variable_name) like below.
    var str1 = "hello"
    var salary:Int = 10000
    let str2 = "\(str1) Jerry, your salary is \(salary)"

    Above code will get below result.

    hello Jerry, your salary is 10000

3. Check Whether String Variable Is Empty Or Not.

The swift String class’s instance property isEmpty return a boolean value to indicate whether the string variable contains character or not.

var str1 = String()

str1 = "hello world"

var str2 = ""

print("str1 isEmpty return \(str1.isEmpty)")

print("str2 isEmpty return \(str2.isEmpty)")

Below is the code execution result.

str1 isEmpty return false
str2 isEmpty return true

4. Return String Text Length.

The String class’s instance property count will return the string text length.

var str1 = String()

str1 = "hello world"

var len = str1.count

print("str1's length is \(len)")

Below is the execution result.

str1's length is 11

5. String Compare.

The string compare will compare each character’s ascii code of the string in order.

// check whether str1 equals str2.
var str1 = "hello"

var str2 = "hello"

if(str1 == str2){
    print("str1 equals str2.")
    print("str1 dose not equals str2.")

// check whether str3 is bigger than str1.
var str3 = "world"

if(str3 > str1){
    print("str3 > str1")
}else if(str3 < str1){
    print("str3 < str1")
    print("str3 = str1")

Below is the code execution result.

str1 equals str2.
str3 > str1

6. Check String Prefix & Suffix.

String class’s hasPrefix & hasSuffix method is used to check whether the string text has the prefix string or suffix string.

var str = ""

    print("This is a http website.")

    print("This is not a jpg image.")

Below is the code execution result.

This is a http website.
This is not a jpg image.

7. Convert String To Uppercase & Lowercase.

String class’s uppercased & lowercased method is used to convert string content to uppercase or lowercase.

let str = "Hello World"



Below is the code execution result.

hello world

8. Convert Other Data Type Value To String.

You can use the swift string interpolation to insert any data type value to create a new string.

var a = 2
var b = "\(a) * 3 = \(Float(a) * 3)"

Below is the code execution result.

2 * 3 = 6.0

9. Convert String To Other Data Type Value.

9.1 Use Swift Int Or Double Structure.

var a:String = "100"

var b:Int? = Int(a)

var c:Double? = Double(a)



Below is the execution result.


9.2 Use Cocoa NSString Class.

// first to import Cocoa library which contains NSString class.
import Cocoa

// declare a string variable that content is an integer.
var a:String = "100"

// convert a swift String type to NSString type.
var ns = a as NSString

// invoke NSString method to get integer or double value.


Below is the code execution result.


Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.