Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use String Characters in Swift
Written by Team Kodeco

A string in Swift is a collection of characters and you can access individual characters in a string using the String.Index type.

Here’s how to use string characters in Swift:

let greeting = "Hello, World!"

// You can access the first character of a string using the startIndex property
let firstCharacter = greeting[greeting.startIndex]
print(firstCharacter) // Output: "H"

// You can access the last character of a string using the endIndex property
let lastCharacter = greeting[greeting.index(before: greeting.endIndex)]
print(lastCharacter) // Output: "!"

// You can access a specific character in a string using the index(:offsetBy:) method
let thirdCharacter = greeting[greeting.index(greeting.startIndex, offsetBy: 2)]
print(thirdCharacter) // Output: "l"

You can also use a for-in loop to iterate over the characters in a string:

for character in greeting {
  print(character)
}
© 2024 Kodeco Inc.