What is a character?
A character is a single symbol (letter, number, etc.). Character in swift are of Character
type and is declared as:
let someCharacter:Character
How to declare and assign a character in Swift?
You can assign value in Character type same as String using double quotes " "
but it should contain only a single character inside the quotes " "
.
If you need to include more than one character you need to define it String
instead of Character
.
Example 1: Declaring and assigning a character
let someCharacter:Character = “H”
let specialCharacter:Character = “@”
print(someCharacter)
print(specialCharacter)
When you run the program, the output will be:
H @
Example 2: Assigning more than one character (Doesn’t work)
But if you try to assign two symbols inside the character as
/*
This will give an error
Changing the type to String will fix it.
*/
let failableCharacter:Character = "H@"
print(failableCharacter)
When you try to run the above code, you will get an error as:
Cannot convert value of type String to Character.
Creating character using unicode and escape sequence
You can also create special type of characters for.e.g emoji using unicodes. You can create a unicode using escape sequence \u{n} (unicode code point ,n is in hexadecimal).
Example 3: Creating a unicode character
let heartShape:Character = "\u{2665}"
print(heartShape)
When you run the program, the output will be:
♥
In the above example, a heart shape character was created from code U+2665
. Although \u{2665}
is included in double quotes, compiler doesn't treat it as a String
because we used escape sequence \u{n}
. An escape sequence doesn’t represent itself when included in literal.
What is a String?
A string is simply a collection of characters. Strings in Swift are of String
type and declared as:
let someString:String
How to declare and assign a string in Swift?
You can assign value in String type using string literals. A string literal is a collection of characters surrounded with double quotes " "
.
Example 4: Declaring and assigning a string
let someString:String = "Hello, world!"
let someMessage = "I love Swift."
print(someString)
print(someMessage)
When you run the program, the output will be:
Hello, world! I love Swift.
Here, both "Hello, world!"
and "I love Swift."
are string literals used to create string variables someString and someMessage respectively.
Operations on a string
There are some built in functions and property in String to deal with most frequently used operations. For example: to join strings, change it to uppercase or capitalize it. Let's explore some frequently used operations below:
String comparison
You can simply check if two strings are equal or not using comparison operator (==)
. The operator returns returns true
if both strings are equal, otherwise it returns false
.
Example 5: String comparison in Swift
let someString = "Hello, world!"
let someMessage = "I love Swift."
let someAnotherMessage = "Hello, world!"
print(someString == someMessage)
print(someString == someAnotherMessage)
When you run the program, the output will be:
false true
String concatenation
Two different strings value can be added together with the addition operator (+)
or using compound assignment operator (+=)
. You can also append a character/string in a string using append
method.
Example 6: String concatenation in Swift
let helloStr = "Hello, "
let worldStr = "World"
var result = helloStr + worldStr
print(result)
result.append("!")
print(result)
When you run the program, the output will be:
Hello, World Hello, World!
In the above program we created a string result by appending helloStr and worldStr using + operator. So, print(result)
outputs Hello, World in the screen.
You can also append any character or string using append
method. result.append("!")
appends a !
character at the end of the string. So, print(result)
outputs Hello, World! on the screen.
String concatenation using advanced assignment operator
We can also use advanced assignment operator (+=) to append string.
Example 7: String concatenation using += operator
var helloStr = "Hello, "
let worldStr = "World!"
helloStr += worldStr
print(helloStr)
When you run the program, the output will be:
Hello, World!
Notice the use of var instead of let in helloStr. If you have defined helloStr a constant using let, you cannot change it later using the +=
operator and eventually get an error. So, you have to define helloStr a variable.
String Interpolation
It is a simple process of evaluating a string literal that consists of variables, constants etc. Imagine you have player’s name and score stored in two constants as:
let playerName = "Jack" let playerScore = 99
Now you need to display a message to the player as "Congratulations Jack!. Your highest score is 99." Here, you need to a way to use the values of the constants in a single string.
This can be achieved using string concatenation as:
let congratsMessage = "Congratulations " + playerName + "!. Your highest score is " + playerScore + "."
print(congratsMessage)
However, you can see this can get messy pretty soon. You have to take care of the spaces after the word Congratulations
, is
. Also, if you have to use more than two constants/variables, it will get unreadable.
There’s an easier way to display the message using string interpolation. Interpolation is the process to include value of a variable or constant inside string literal.
The variable or constant that should insert into the string literal is wrapped in a pair of parentheses ( )
, prefixed by a backslash (\)
.
Example 8: String interpolation in Swift
let playerName = "Jack"
let playerScore = 99
let congratsMessage = "Congratulations \(playerName)!. Your highest score is \(playerScore)."
print(congratsMessage)
When you run the program, the output will be:
Congratulations Jack!. Your highest score is 99.
Some helpful built-in String functions & variables:
1. isEmpty
This function determines if a string is empty or not. It returns true
if the string is empty otherwise, it returns false
.
Example 9: isEmpty
var emptyString = ""
print(emptyString.isEmpty)
When you run the program, the output will be:
true
2. capitalized
This property is used to capitalize every word in a string.
Example 10: capitalized
let someString = "hello, world!"
print(someString.capitalized)
When you run the program, the output will be:
Hello, World!
3. uppercased and lowercased
The uppercased function converts string to uppercase letter and the lowercased function converts string to lowercase letter.
Example 11: uppercased() and lowercased()
let someString = "Hello, World!" print(someString.uppercased()) print(someString.lowercased())
When you run the program, the output will be:
HELLO, WORLD! hello, world!
4. Length/count
This property is used to count the total number of characters in a string.
Example 12: count
let someString = "Hello, World!"
print(someString.count)
When you run the program, the output will be:
13
5. hasPrefix
This function determines if a string starts with certain characters or not and returns a boolean value. It returns true
if the string prefix matches with the provided value otherwise returns false
.
Example 13: hasPrefix()
let someString = "Hello, World!"
print(someString.hasPrefix("Hell"))
print(someString.hasPrefix("hell"))
When you run the program, the output will be:
true false
6. hasSuffix
This function determines if a string ends with certain characters or not and returns a boolean value. It returns true
if the string suffix matches with the provided value otherwise returns false
.
Example 14: hasSuffix()
print(someString.hasSuffix("rld!"))
print(someString.hasSuffix("Rld!"))
When you run the program, the output will be:
true false