Swift Character
Character is a data type that represents a single-character string ("a"
, "@"
, "5"
, etc).
We use the Character
keyword to create character-type variables in Swift. For example,
var letter: Character
Here, the letter
variable can only store single-character data.
Character Example
// create character variable
var letter: Character = "H"
print(letter) // H
var symbol: Character = "@"
print(symbol) // @
In the above example, we have created two character variables: letter
and symbol
. Here, we have assigned "H"
to letter
and "@"
to symbol
.
Note: If we try to assign more than one character to a Character
variable, we will get an error.
// create character variable
let test: Character = "H@"
print(test)
// Error:
// cannot convert value of type 'String' to specified type Character
Swift String
In Swift, a string is used to store textual data ("Hey There!"
, "Swift is awesome."
, etc).
We use the String
keyword to create string-type variables. For example,
let name: String
Here, the name variable can only store textual data.
Note: Since a string contains multiple characters, it is called a sequence of characters.
String Example
// create string type variables
let name: String = "Swift"
print(name)
let message = "I love Swift."
print(message)
Output
Swift I love Swift.
In the above example, we have created string-type variables: name and message with values "Swift"
and "I love Swift"
respectively.
Notice the statement,
let message = "I love Swift."
Here, we haven't used the String
keyword while creating the variable. It is because Swift is able to infer the type based on the value.
Note: In Swift, we use double quotes to represent strings and characters.
String Operations
The String
class in Swift provides various built-in functions that allow us to perform different operations on strings.
1. Compare Two Strings
We use the ==
operator to compare two strings. If two strings are equal, the operator returns true
. Otherwise, it returns false
. For example,
let str1 = "Hello, world!"
let str2 = "I love Swift."
let str3 = "Hello, world!"
// compare str1 and str2
print(str1 == str2)
// compare str1 and str3
print(str1 == str3)
Output
false true
In the above example,
str1
andstr2
are not equal. Hence, the result is false.str1
andstr3
are equal. Hence, the result is true.
2. Join Two Strings
We use the append()
function to join two strings in Swift. For example,
var greet = "Hello "
var name = "Jack"
// using the append() method
greet.append(name)
print(greet)
Output
Hello Jack
In the above example, we have used the append()
method to join name and greet.
Concatenate Using + and +=
We can also use the +
and +=
operators to concatenate two strings.
var greet = "Hello, "
let name = "Jack"
// using + operator
var result = greet + name
print(result)
//using =+ operator
greet += name
print(greet)
Output
Hello, Jack Hello, Jack
In the above example, we have used the +
and +=
operators to join two strings: greet
and name
.
Note: We cannot create greet
using let
. It is because the +=
operator joins two strings and assigns the new value to greet
.
3. Find Length of String
We use the count
property to find the length of a string. For example,
let message = "Hello, World!"
// count length of a string
print(message.count) // 13
Note: The count
property counts the total number of characters in a string including whitespaces.
Other Built-in Functions
Built-in function | Description |
---|---|
isEmpty |
determines if a string is empty or not |
capitalized |
capitalizes the first letter of every word in a string |
uppercased() |
converts string to uppercase |
lowercased() |
converts string to lowercase |
hasPrefix() |
determines if a string starts with certain characters or not |
hasSuffix() |
determines if a string ends with certain characters or not |
Escape Sequences
The escape sequence is used to escape some of the characters present inside a string.
Suppose we need to include double quotes inside a string.
// include double quote
var example = "This is "String" class"
print(example) // throws error
Since strings are represented by double quotes, the compiler will treat "This is "
as the string. Hence, the above code will cause an error.
To solve this issue, we use the escape character \
in Swift.
// use the escape character
var example = "This is \"String\" class"
print(example)
// Output: This is "String" class
Now the program will run without any error. Here, the escape character will tell the compiler to ignore the character after \
.
Here is a list of all the escape sequences supported by Swift.
Escape Sequences | Character |
---|---|
\0 |
null |
\\ |
plain backslash |
\t |
a horizontal tab |
\n |
line feed |
\" |
double quote |
String Interpolation
We can also use the backslash character \
to use variables and constants inside a string. For example,
let name = "Swift"
var message = "This is \(name) programming."
print(message)
Output
This is Swift programming.
In the above example, notice the line
var message = "This is \(name) programming."
Here, we are using the name
variable inside the string message
. This process is called String Interpolation in Swift.
Swift Multiline String
We can also create a multiline string in Swift. For this, we use triple double quotes """
. For example,
// multiline string
var str: String = """
Swift is awesome
I love Swift
"""
print(str)
Output
Swift is awesome I love Swift
In the above example, anything inside the enclosing triple-quotes is one multiline string.
Note: Multi-line strings must always begin on a new line. Otherwise, it will generate an error.
// error code
var str = """Swift
I love Swift
"""
Create String Instance
We can also create a string using an initializer syntax. For example,
var str = String()
Here, the initializer syntax String()
will create an empty string.