English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn about the usage of characters and strings in Swift. You will also learn about the different operations that can be performed on strings and characters.
Characters are single symbols (letters, numbers, etc.). In Swift, characters are of Character type and are declared as:
let someCharacter: Character
You can use double quotes "" to specify a value of the same character type as a string, but only one character can be included within the quotes.
If you need to include multiple characters, you need to define them as a String type instead of Character.
let someCharacter: Character = "H" let specialCharacter: Character = "@" print(someCharacter) print(specialCharacter)
When running the program, the output is:
H @
But if you try to assign two symbols as
/* This will result in an error. Changing the type to String can fix the problem. */ let failableCharacter: Character = "H@" print(failableCharacter)
When you try to run the above code, you will receive the following error message:
Cannot convert value of type String to Character. (Cannot convert a string type value to a character.)
You can also use unicodes to create special types of characters for emoji emoticons. You can use the escape sequence \u {n} to create Unicode (Unicode code point, n is hexadecimal).
let heartShape: Character = "\u{2665" print(heartShape)
When running the program, the output is:
♥
In the above example, from the code U + 2665A heart-shaped character was created. Although \u {2665}} is enclosed in double quotes, but the compiler does not treat it as String because we used the escape sequence \u {n}. Escape sequences within literals do not represent themselves.
Strings are just collections of characters. In Swift, strings are of the String type and are declared as:
let someString: String
You can useString LiteralsAssign values with the String type. String literals are a collection of characters enclosed in double quotes "".
let someString: String = "Hello, world!" let someMessage = "I love Swift." print(someString) print(someMessage)
When running the program, the output is:
Hello, world! I love Swift.
Here, 'Hello, world!' and 'I love Swift.' are strings used to create string variables someString and someMessage.
String has some built-in functions and properties to handle the most common operations. For example: to concatenate strings, change them to uppercase or uppercase. Let's explore some common operations below:
You can useComparison Operators (==) Simply check if two strings are equal. If the two strings are equal, the operator returns true, otherwise it returns false.
Example5String Comparison in Swift
let someString = "Hello, world!" let someMessage = "I love Swift." let someAnotherMessage = "Hello, world!" print(someString == someMessage) print(someString == someAnotherMessage)
When running the program, the output is:
false true
You can useaddition operator (+) or usecompound assignment operator (+=) to add two different string values together. You can also use the append method to add a character to a string/String.
Example6String Concatenation in Swift
let helloStr = "Hello, " let worldStr = "World" var result = helloStr + worldStr print(result) result.append("!") print(result)
When running the program, the output is:
Hello, World Hello, World!
In the above program, we attached and used+operator creates aString result. Therefore, helloStrworldStrprint(result) outputsHello, World.
You can also use the append method to attach any character or string. result.append("!") attaches a ! character at the end of the string. Therefore, print(result) outputsHello, World!.
String Concatenation with Advanced Assignment Operators
We can also use advanced assignment operators (+ =) to concatenate strings.
Example7Use+ String Concatenation with = operator
var helloStr = "Hello, " let worldStr = "World!" helloStr += worldStr print(helloStr)
When running the program, the output is:
Hello, World!
Note that var is used instead of let in helloStr. If you have already defined helloStr as a constant using let, you cannot use +The = operator changes it and eventually results in an error. Therefore, you must define the helloStr variable.
This is a simple process, a string literal that includes variables, constants, and so on. Suppose you have a player's name and score stored in two constants as follows:
let playerName = "Jack" let playerScore = 99
Now, you need to display a message to the player, “CongratulationsJack!Your highest score is99"."
This can be achieved by using string concatenation:
let congratsMessage = "Congratulations" + playerName + "!. Your highest score is" + playerScore + "." print(congratsMessage)
However, the readability of the above method is poor.
So, there is an easy way to display messages using string interpolation. Interpolation is the process of including the value of a variable or constant in a string literal.
Variables or constants to be inserted into a string literal should be enclosed in a pair of parentheses ( ) and prefixed with a backslash (\).
let playerName = "Jack" let playerScore = 99 let congratsMessage = "Congratulations\(playerName)!. Your highest score is \(playerScore)." print(congratsMessage)
When running the program, the output is:
Congratulations, Jack! Your highest score is 99.
This function determines whether a string is empty. It returns true if the string is empty, otherwise it returns false.
var emptyString = "" print(emptyString.isEmpty)
When running the program, the output is:
true
This property is used to capitalize each word in a string.
let someString = "hello, world!" print(someString.capitalized)
When running the program, the output is:
Hello, World!
The uppercased function converts a string to uppercase letters, and the lowercased function converts a string to lowercase letters.
let someString = "Hello, World!" print(someString.uppercased()) print(someString.lowercased())
When running the program, the output is:
HELLO, WORLD! hello, world!
This property is used to calculate the total number of characters in a string.
let someString = "Hello, World!" print(someString.count)
When running the program, the output is:
13
This function determines whether a string starts with a specific character and returns a boolean value. If the string prefix matches the provided value, it returns true; otherwise, it returns false.
let someString = "Hello, World!" print(someString.hasPrefix("Hell")) print(someString.hasPrefix("hell"))
When running the program, the output is:
true false
This function determines whether a string ends with a specific character and returns a boolean value. If the string suffix matches the provided value, it returns true, otherwise returns false.
print(someString.hasSuffix("rld!")) print(someString.hasSuffix("Rld!"))
When running the program, the output is:
true false