Swift Strings

Swift Introduction

🧵 Swift Strings

In Swift Strings is used to store and work with text.

Swift strings are powerful, Unicode-safe, and easy to use.


🔹 1. What is a String?

A String is a collection of characters.

let name = "Swift"

🔹 2. Creating Strings

String Literal

let greeting = "Hello, Swift!"

Empty String

var text = ""
var message = String()

🔹 3. Printing Strings

let city = "Delhi"
print(city)

🔹 4. String Interpolation (Very Important 🔥)

Insert values inside strings using \( ).

let age = 25
print("My age is \(age)")

✔ Safe
✔ Clean
✔ Recommended


🔹 5. Concatenating Strings

Using +

let first = "Hello"
let second = "Swift"
let result = first + " " + second
print(result)

Using +=

var text = "Hello"
text += " World"
print(text)

🔹 6. Multi-line Strings

Use triple quotes """.

let description = """
Swift is powerful.
Swift is fast.
Swift is easy.
"""

print(description)

🔹 7. String Length

Use .count.

let word = "Swift"
print(word.count)

Output:

5

🔹 8. Checking Empty String

let str = ""

if str.isEmpty {
print(“String is empty”)
}


🔹 9. Accessing Characters

let name = "Swift"
print(name[name.startIndex]) // S

⚠️ Direct indexing like name[0] is not allowed in Swift.


🔹 10. Common String Methods

let text = "Hello Swift"
Method Example Result
Uppercase text.uppercased() HELLO SWIFT
Lowercase text.lowercased() hello swift
Contains text.contains("Swift") true
Has Prefix text.hasPrefix("Hello") true
Has Suffix text.hasSuffix("Swift") true

🔹 11. Comparing Strings

let a = "Swift"
let b = "Swift"
print(a == b) // true


🔹 12. Convert String to Number

let str = "100"
let num = Int(str)
print(num ?? 0)

❌ Common Mistakes

❌ Adding string with number:

print("Age: " + 25) // Error

✅ Correct:

print("Age: \(25)")

🧠 Summary

  • Strings store text data

  • Use " for strings

  • Use \( ) for interpolation

  • .count for length

  •  strings are Unicode-safe

You may also like...