← Swift EnglishChapter 07 of 13

Strings

## Learning Objectives - Create and manipulate strings - Use string interpolation - Work with Unicode - Master string methods and properties ## String Basics ### Creating Strings ```swift let empty = "" let empty2 = String() let greeting = "Hello, World!" let name = "Swift" ``` ### Multiline Strings ```swift let poem = """ Roses are red, Violets are blue, Swift is awesome, And so are you! """ ``` ### Raw Strings ```swift let raw = #"String with "quotes" and \escape"# let path = #"C:\Users\names"# ``` ## String Properties ### Basic Properties ```swift let str = "Hello" str.count // 5 str.isEmpty // false str.first // Optional("H") str.last // Optional("o") ``` ### Unicode Properties ```swift let emoji = "" emoji.count // 1 emoji.unicodeScalars.count // 2 (uses two scalar values) emoji.utf8.count // 4 bytes emoji.utf16.count // 2 code units ``` ## String Indexing ### Access by Position ```swift let greeting = "Hello" let first = greeting[greeting.startIndex] // "H" let last = greeting[greeting.index(before: greeting.endIndex)] // "o" let fifth = greeting[greeting.index(greeting.startIndex, offsetBy: 4)] // "o" ``` ### Safe Access ```swift let greeting = "Hello" // Check bounds first if greeting.count > 3 { let fourth = greeting[greeting.index(greeting.startIndex, offsetBy: 3)] print(fourth) // "l" } ``` ### Iterate Characters ```swift for char in "Hello" { print(char) } // H // e // l // l // o ``` ## Substrings ### Creating Substrings ```swift let greeting = "Hello, World!" let start = greeting.index(greeting.startIndex, offsetBy: 7) let end = greeting.index(greeting.endIndex, offsetBy: -1) let substring = greeting[start..

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →