SwiftSnippet
Last updated at 2023-09-04

Easy Swift String Index Tutorial

ClickUp
Note
AI Status
Full
Last Edit By
Last edited time
Sep 4, 2023 12:57 PM
Metatag
Slug
swift-string-index-tutorial
Writer
Published
Published
Date
Aug 3, 2023
Category
Swift
Snippet
Swift String Index takes grapheme clusters into account. It means it respects the presence of Unicode characters in your String.
āœ… get first character from šŸ‘Øā€šŸ‘©ā€šŸ‘¦ == šŸ‘Øā€šŸ‘©ā€šŸ‘¦ āœ… get second character from šŸ‘Øā€šŸ‘©ā€šŸ‘¦ == index out of bounds
In Javascript, you get the unicode character.
"šŸ‘Øā€šŸ‘©ā€šŸ‘¦"[0] == '\uD83D'

Get character at Int index

let intIndex = 3 let input = "This is emoji family šŸ‘Øā€šŸ‘©ā€šŸ‘¦" let index = input.index(input.startIndex, offsetBy: intIndex) let char = input[index] print(char) // prints "s"

Convert Int to String.Index

input.index(input.startIndex, offsetBy: 3)
The above code will convert 3 to the corresponding String.Index of input.

Negative offset from .endIndex

let intIndex = -3 let input = "This is emoji family" let index = input.index(input.lastIndex, offsetBy: intIndex) let char = input[index] print(char) // prints "i"
Ā 

Discussion (0)

Related Posts