Count and Indices
Part of the Logic & Flow section of Coddy's Swift journey — lesson 1 of 56.
You've used str.count in fundamentals to get the number of characters. Going further means understanding that a Swift String is a sequence of Characters, not a flat array of bytes.
let greeting = "Hello"
print(greeting.count) // 5
print(greeting.first!) // "H"
print(greeting.last!) // "o"
print(greeting.isEmpty) // falseYou can't index a string with an integer. To grab a character at a specific position, ask the string for an index offset from its start:
let i = greeting.index(greeting.startIndex, offsetBy: 1)
print(greeting[i]) // "e"The first, last, and isEmpty properties are the everyday tools. Reach for indices only when you really need a specific position.
Challenge
BeginnerRead a single line of input. Print three lines:
- The number of characters in the input
- The first and last character separated by a space, e.g.
H oforHello truewhen the first and last characters are the same letter ignoring case, otherwisefalse(e.g.Anna,RadaR)
Assume the input has at least one character.
For input RadaR, the output is:
5
R R
trueCheat sheet
A Swift String is a sequence of Characters. Key properties:
let s = "Hello"
s.count // 5
s.first! // "H"
s.last! // "o"
s.isEmpty // falseTo access a character at a specific position, use an index offset:
let i = s.index(s.startIndex, offsetBy: 1)
print(s[i]) // "e"Case-insensitive character comparison:
s.first!.lowercased() == s.last!.lowercased()Try it yourself
let line = readLine()!
// TODO: print count, first/last, and same-letter-ignoring-case check
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check