Menu
Coddy logo textTech

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)          // false

You 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 icon

Challenge

Beginner

Read a single line of input. Print three lines:

  1. The number of characters in the input
  2. The first and last character separated by a space, e.g. H o for Hello
  3. true when the first and last characters are the same letter ignoring case, otherwise false (e.g. Anna, RadaR)

Assume the input has at least one character.

For input RadaR, the output is:

5
R R
true

Cheat 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     // false

To 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow