String
can be defined as a collection of Characters into a single variable.
1
| var str: String = "This is a String"
|
Character
is a single value of a String
1
| var chat: Character = "!"
|
- Both are defined using
""
, but for Character
we have to explicitly define the type otherwise the Swift compiler will infer it as a String
You can add Strings to Strings but not Character to Strings.
1
2
3
4
| var str1 = "This is a "
var str2 = "String"
var str = str1 + str2
print(str)
|
You can convert a Character or a array or Characters in to a String
1
2
3
| var charArray: [Character] = ["S", "t", "r", "i", "n", "g"]
var charStr = String(charArray)
print(charStr)
|
Multi-line Strings
Multiline Strings are defined using """
in Swift.
1
2
3
4
5
| var multilineStr = """
This is a multiline String.
I am the second line
"""
print(multilineStr)
|
1
2
| This is a multiline String.
I am the second line
|
The first new line is not shown as new a line. To create an extra line at top and bottom we need to leave an extra line empty.
1
2
3
4
5
6
7
| var multilineStr = """
This is a multiline String.
I am the second line
"""
print(multilineStr)
|
1
2
3
4
|
This is a multiline String.
I am the second line
|
String interpolation
Mixing different types while creating a String without converting other types to String explicitly. You can also add expressions while interpolation String.
1
2
3
4
5
| var name:String = "John"
var age:Int = 37
var height: Double = 178.6
var isTall: Bool = height > 170
print("\(name) is \(age) years old and is \(height) cms tall. He is of a \(isTall ? "good" : "short") height")
|
1
| John is 37 years old and is 178.6 cms tall. He is of a good height
|
Iterating over a String
When we iterate over a String to get individual elements from it, we get them as Character
type.
1
2
3
4
| var name:String = "John"
for n in name {
print(type(of: n))
}
|
1
2
3
4
| Character
Character
Character
Character
|
Substrings
We can create Substrings from a String using different methods provided by the String or by subscripting.
- When we create a substring, the result that we get is of type
Substring
. - It holds most of the same methods as
String
but its purpose is for short usage. - If we want to use the substring for longer periods, we should convert it into a String
1
2
3
4
| var longString: String = "ThisIsJustALongContinuesString"
var jIndex = longString.firstIndex(of: "J") ?? longString.endIndex
var subString = longString[..<jIndex]
print("\(subString) is of Type \(type(of: subString))")
|
1
| ThisIs is of Type Substring
|
- Substring usually will occupy the same memory space from the original String to optimize the use of memory untill you modify the original String or the Substring.