Learn/Swift/8. Strings and a small project
Lesson 8 of 8
Sign in

Swift, lesson 8

Strings and a small project

Text is everywhere: names, messages, commands, whole documents. Swift's String is a value type (copying one gives you an independent copy) and it is fully Unicode-aware. This lesson covers the operations you will reach for most, then puts lessons 1 to 7 together in a small project.

Looking at a string

count counts characters as a person sees them, so an emoji or an accented letter counts as one, even if it takes several bytes in memory. Comparing strings with == checks whether they read the same, and < compares alphabetically (capital letters sort before lowercase ones).

Characters

A string is a sequence of Character values, so a for-in loop visits each one. Characters can answer questions about themselves:

2 exercises to try what you just read.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Word statistics

Press Ctrl Enter or Check to test your code.

You can build a new string by starting empty and calling append(_:) with characters or other strings.

One surprise: you cannot write title[0]. Because characters have different sizes, Swift does not let you jump to a position with a plain Int. Instead, use the properties first and last (optionals), prefix(_:) and suffix(_:) for the first or last few characters, or loop.

Transforming text

Strings are not changed in place by these methods; each returns a new value:

reversed() gives a reversed sequence of characters, so wrap it in String(...) to get text back.

Splitting and joining

split(separator:) breaks a string into pieces and skips empty pieces, so several spaces in a row do not produce empty words. The pieces are Substring values, a lightweight view into the original string; turn one into a full String with String(piece) when you want to keep it. joined(separator:) goes the other way and glues an array of strings together:

Putting it together

The final exercise is a small text-statistics tool. Before writing code, plan it in steps, each of which you already know how to do:

  1. Read every line until the input ends (while let from lesson 5) and count them.
  2. Split each line into pieces and clean each piece with a function (lesson 6) that keeps only letters and lowercases them.
  3. Store the cleaned words in an array and count them in a dictionary (lesson 7).
  4. Find the longest word and the most common word with a loop and some if checks (lesson 4).
  5. Print the report with string interpolation (lessons 1 and 2).

Breaking a problem into small, testable steps like this is most of what programming is.

Further reading

  • Strings and Characters
  • Collection Types
  • String in the standard library

A palindrome reads the same forwards and backwards. Read one line of text and decide whether it is a palindrome when you look only at letters and digits and ignore case. So Never odd or even and A man, a plan, a canal: Panama! both count.

Input: one line of text with at least one letter or digit.

Output: Yes or No.

Sample input:

Sample output:

Build a word-statistics report for a piece of text.

Input: zero or more lines of text.

How to find the words: split each line on spaces. From each piece, keep only the letters (isLetter) and lowercase them, so Swift, becomes swift and Don't becomes dont. If nothing is left, the piece is not a word.

Output: exactly five lines:

If several words share the top count, pick the one that comes first alphabetically. When there are no words at all, print Longest: none and Top: none for the last two lines.

Sample input:

Sample output:

let title = "Swift Notes"
print(title.count)              // 11 characters
print(title.isEmpty)            // false
print(title.hasPrefix("Swift")) // true
print(title.hasSuffix("!"))     // false
print(title.contains("Note"))   // true
var letters = 0
var digits = 0
for ch in "R2-D2 rocks" {
    if ch.isLetter {
        letters += 1
    } else if ch.isNumber {
        digits += 1
    }
}
print(letters, digits)   // 7 2
let shout = "quiet please".uppercased()      // "QUIET PLEASE"
let calm = "STOP".lowercased()               // "stop"
let backwards = String("stressed".reversed()) // "desserts"
let line = String(repeating: "=", count: 5)  // "====="
let words = "red  green blue".split(separator: " ")   // 3 pieces
let csv = ["red", "green", "blue"].joined(separator: ",") // "red,green,blue"
Never odd or even
Yes
Lines: <number of input lines>
Words: <number of words>
Unique: <number of different words>
Longest: <the longest word; if several tie, the one that appears first>
Top: <the most common word> (<its count>)
Swift is fun, and Swift is fast!
Is it? Yes.
Lines: 2
Words: 10
Unique: 7
Longest: swift
Top: is (3)