In this tutorial you will learn about the Swift Strings and its application with practical example.
Swift Strings
String is a series or sequence of characters, a string variable is used to hold string value that could be consists of letters, numbers, and any special characters.
Example:-
Below is a list of some valid string –
1 |
"Hello, World!", "Welcome to W3Adda", "Swift Tutorials" etc. |
Declaring Strings In Swift
In Swift, a strings can be declared using double quotes “Hello World”.
Syntax:-
1 |
var <str_var_name>: <String> = "<any_valid_string" |
Example:-
1 2 |
var mystring = "Hello, World!" print(mystring) |
Output:-
1 |
Hello, World! |
Swift Strings Concatenation
In Swift, strings can be concatenated simply using the plus (‘+’) operator or the +=
assignment operator.
Example:-
1 2 3 4 |
var str1 = "Welcome to " var str2 = "W3Adda" var str3 = str1 + str2 print(str3) |
When you will run above code, you will see the following output.
Output:-
1 |
Welcome to W3Adda |
If you want to append a characters to any string it can be simply done using append() method as following –
Example:-
1 2 3 4 5 |
var str1 = "Welcome to " var str2 = "W3Adda" var str3 = str1 + str2 str3.append("!") print(str3) |
Output:-
Swift Strings Comparison
In swift, equal to (==) and not equal (!=) operators can used to check whether the given two strings are equal or not.
The equality operators will perform case-sensitive comparison which means “HELLO” and “hello” are not equal.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var str1 = "HELLO" var str2 = "hello" var str3 = "Hello" var str4 = "HELLO" if str1 == str2 { print( "\(str1) and \(str2) are equal" ) } else if str1 == str3 { print( "\(str1) and \(str3) are equal" ) } else if str1 == str4 { print( "\(str1) and \(str4) are equal" ) } else { print("No Matching String Found!" ) } |
When you will run above code, you will see the following output.
Output:-
Swift Check Empty Strings
In swift, isEmpty property can be used check if a given string is empty string or not.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
var str1: String = "Hello" var str2: String = "" print("W3Adda - Check empty string using isEmpty") if str1.isEmpty { print("str1 is empty.") } if str2.isEmpty { print("str2 is empty.") } |
When you will run above code, you will see the following output.
Output:-