← All lessonsUnit 1 · Swift for problems
Lesson 1.3

Characters as numbers

A character is not a number, and three conversions get you from one to the other: a letter to its place in the alphabet, a digit to its value, and a number to its characters.

Reach for it when
Letters are counted in 26 slots, or digit characters have to become numbers.
The move
asciiValue gives a letter's number, wholeNumberValue gives a digit's value, and String(n) turns a number back into characters.
Cost
Each is one step.

The idea

Harper

I turned a seven over last night. On the back it said fifty-five.

Arthur

Then it wasn't a number. Numbers don't have backs.

Harper

We'll come back to it. Here is the character "7". Add 1 to it.

Arthur

I can't. It doesn't compile. A character is a picture of a seven, not a seven.

Harper

But it says seven. I can read it.

Arthur

A photograph of a cake says cake. You still can't eat it.

Harper

Then give me a picture I can use.

Arthur

A box of tiles, the kind you spell words with. Every character is a tile, and its face is what you read. A digit tile will hand you its face as a real number, one you can add to: that is wholeNumberValue, and for "7" it is 7.

Harper

And the tile for c? What's that face worth?

Arthur

Nothing. It's a letter, so wholeNumberValue is nil. Turn it over, though. Every plain tile has a number printed on its back, and the lowercase letters were numbered in order: 97 on a, 98 on b, on to 122 on z. That number is asciiValue.

Harper

Who starts counting at 97?

Arthur

A committee. The numbers before it were taken.

Harper

So I take 97 off the back of a letter, and I'm left with…

Arthur

Its place in the alphabet. 0 for a, 25 for z.

Harper

Twenty-six places, 0 to 25. That's an array waiting to happen.

Arthur

It's a tray with 26 slots. To count the letters of a word, turn each tile over, take off 97, and drop it in the slot with that number. Nobody searches for anything. The tile says where it goes.

Harper

And a number like 120? Can I have that in tiles?

Arthur

String(120) spells it: three tiles, 1, 2 and 0. To read a row of digit tiles back, go left to right. Each tile makes what you have ten times bigger, then adds its face.

Harper

Which leaves my seven.

Arthur

You read the wrong side.

Harper

Hold that thought. I'd already put it in the total.

That is the whole tool: a character is not a number, but it carries one on its back, and a digit carries another on its face. The lesson is three conversions: a letter to its place in the alphabet and back, a digit to its value, and a number to its characters and back.

The shape

This is what you know by heart. It counts the letters of a word, and later lessons lean on it more than on anything else here.

Swift
/// How many times each letter is in `word`: slot 0 counts a, and slot 25 counts z.
/// `word` holds only the lowercase letters a to z.
func letterCounts(_ word: String) -> [Int] {
    var counts = Array(repeating: 0, count: 26)      // the tray: 26 slots, all empty
    for letter in word {
        let place = Int(letter.asciiValue!) - 97     // the back of the tile, less a's 97
        counts[place] += 1                           // drop the tile in its slot
    }
    return counts
}

Each of its parts is there for a reason.

The other conversions are one line each. Step by step takes them in turn, and ends at the tray.

Watch it run

The word is cabbage. Each tile is turned over and dropped.

letteron its backplaceits slot after
c9921
a9701
b9811
b9812
a9702
g10361
e10141

The first seven slots, a to g, end as [2, 2, 1, 0, 1, 0, 1], and the other nineteen are still 0. Look at the fourth row. The second b has the same number on its back as the first, so it lands in the same slot, and the slot goes from 1 to 2. That is all the counting there is. Nothing was searched for: each tile's own back said where it goes.

Step by step

Step 1

Is this character a digit? A letter?

Swift
/// What kind of character this is: "digit", "letter" or "other".
func kind(of character: Character) -> String {
    if character.isNumber {
        return "digit"
    }
    if character.isLetter {
        return "letter"
    }
    return "other"
}

What is new: a tile can say what kind of face it has. isNumber is true for a digit, and isLetter for a letter. Both come with Swift's Character, with nothing imported. kind(of: "7") is digit, kind(of: "q") is letter, and kind(of: "?") is other.

In a loop the same two questions pick characters out of a text. Keep each character for which character.isLetter || character.isNumber is true, and Room 42, floor 3! becomes Room42floor3.

One more small step, with a problem of its own. What is new: the two questions are generous. They answer for every alphabet and every kind of number. isLetter is true for é. isNumber is true for ½, and for the raised ² of m², so in 10 m² it finds 3 numbers. When a problem promises ASCII, which is plain tiles and nothing else, this never shows. When it does not, and you mean the ten digits 0 to 9, ask as well whether the tile is plain: character.isASCII && character.isNumber. The ten digits are the only numbers among the plain tiles, so that finds 2 in 10 m².

Step 2

The value of a digit character

Swift
/// What a digit is worth: "7" gives 7. `digit` is one of "0" to "9".
func digitValue(_ digit: Character) -> Int {
    return digit.wholeNumberValue!
}

What is new: wholeNumberValue reads the face of a digit tile as an Int. For "7" it is 7. The back of the same tile is 55: the back says where a tile sits among all the tiles, not what it is worth.

wholeNumberValue is an Int?, because most tiles are not digits: for q it is nil. The ! is right here because the problem promises a digit. When nothing is promised, if let asks "is it a digit?" and takes the value in one line:

Swift
/// The sum of the digits in `text`. Every other character is skipped.
func sumOfDigits(_ text: String) -> Int {
    var total = 0
    for character in text {
        if let value = character.wholeNumberValue {      // a digit, and what it is worth
            total += value
        }
    }
    return total
}

For a1b2c3 this gives 6.

wholeNumberValue is generous in the way isNumber is: for a 4 in a circle, ④, it is 4. Among the plain tiles, the only ones it has a value for are the ten digits.

Step 3

A letter's place in the alphabet

Swift
/// Where a lowercase letter is in the alphabet: a is 0, and z is 25.
func place(of letter: Character) -> Int {
    return Int(letter.asciiValue!) - 97
}

What is new: asciiValue, the number on the back of a tile. The lowercase letters are numbered in order with no gaps: a is 97, c is 99 and z is 122. So a letter's back, less 97, is how far it is past a: 0 for a, 2 for c and 25 for z.

Its type is UInt8?, and each half of that is a trap.

The ?. Only the plain tiles have a number on the back. For é, asciiValue is nil, and ! on that stops the program. So ! is for a problem that promises lowercase English letters, as this step's first problem does.

The UInt8. It holds 0 to 255 and nothing below zero. The back of a capital A is 65. Take 97 from it as an Int and you get -32, an ordinary number that you can test and turn away. Take 97 from it as a UInt8 and there is no such number, so the program stops. That is why the line says Int(…) first and subtracts second.

One more small step. What is new: when nothing is promised, test the place before you trust it.

Swift
/// Where `character` is in the alphabet, or nil when it is not one of a to z.
func carefulPlace(of character: Character) -> Int? {
    if let number = character.asciiValue {      // nil for a tile such as é
        let place = Int(number) - 97            // may be below 0, or above 25
        if place >= 0 && place < 26 {
            return place
        }
    }
    return nil
}

It gives 2 for c, and nil for a capital C and for é. This step's second problem hands you this function with one line that stops the program, to mend.

The digit tiles are numbered in order too, from 48 for "0", which is why the back of "7" is 55. So a digit's back, less 48, is its value. wholeNumberValue gives the same answer with no number to remember.

Step 4

The letter for a place

Swift
/// The lowercase letter at a place in the alphabet: 0 gives a, and 25 gives z.
func letter(at place: Int) -> Character {
    return Character(UnicodeScalar(UInt8(97 + place)))
}

What is new: the way back, from a number to its tile. Read it from the inside out. 97 + place is the number for the back. UInt8(…) makes it the kind of number a back is. UnicodeScalar(…) finds the character with that number, and Character(…) hands it over as a tile. letter(at: 2) is c, and letter(at: 25) is z.

The UInt8(…) has a job. Every UInt8 is the number of some character, so UnicodeScalar always finds one. Hand it an Int and it gives back an optional, because most large numbers belong to no character, and the line does not compile.

In a loop over the places 0, 1, 2 and so on, appending each letter to a string, it spells the alphabet: five places give abcde.

Step 5

The characters of a number

Swift
/// The characters that spell `number`: 120 gives "1", "2", "0".
func characters(of number: Int) -> [Character] {
    return Array(String(number))
}

What is new: String(number) spells a number in tiles, and Array(…), from the lesson "A string as an array of characters", sets them out one to a position. For 120 this gives ["1", "2", "0"]: 3 characters, and not one of them is a number yet. Loop over them, read each face with step 2's digit.wholeNumberValue!, and you have the digits as numbers: [1, 2, 0].

The problems for this step promise a number that is 0 or more, because a minus sign is a tile too. -45 spells as ["-", "4", "5"], and the face of "-" is worth nil.

Step 6

A number from its digit characters, multiplying by ten as you go

Swift
/// The number that a string of digits spells: "120" gives 120.
func readNumber(_ digits: String) -> Int {
    var number = 0
    for digit in digits {
        number = number * 10 + digit.wholeNumberValue!     // one column left, then add
    }
    return number
}

What is new: the line number = number * 10 + …. The tiles are read from the left. Each one pushes what you have one column to the left, which is times ten, and then adds its own face. Here it is for 120:

digitnumber beforetimes tenplus the digit
1001
211012
012120120

It gives 120: step 5 undone. number starts at 0, and ten times 0 is 0, so the first tile needs no special case.

Leave the ten out and the faces are only added up: 3. One of this step's problems hands you that version to mend, and another asks for the last column of the table.

Swift does all of this in one call, Int("120"), and in an app that is what you would write. Problems make you do it by hand because the digits arrive one at a time, in among other characters. Then step 2's if let goes round the line:

Swift
/// The number in `text`, read from its digits alone: "1,200" gives 1200.
func readNumber(in text: String) -> Int {
    var number = 0
    for character in text {
        if let value = character.wholeNumberValue {      // a digit: one column left, add
            number = number * 10 + value
        }
    }
    return number
}

For 1,200 this gives 1200. The comma has no value on its face, so it is skipped.

The largest Int has 19 digits. A string of 18 digits always fits in one, and the problems promise no more than that. The lesson "Whole-number arithmetic" has what happens to a number that does not fit.

Step 7

Count each letter of a word into an array of 26 slots

This step is the shape itself, written from an empty function. Its loop and its place are old. What is new: the tray, an array in which the position means a letter.

It is three moves.

  • Make the tray. var counts = Array(repeating: 0, count: 26). Nothing in it says "letter". The meaning is in the positions: slot 0 is for a, slot 1 for b, and slot 25 for z.
  • Find the slot. let place = Int(letter.asciiValue!) - 97, which is step 3.
  • Drop the tile. counts[place] += 1.

Say the sentence that stays true as the loop runs: each slot holds how many times its letter has been met so far. It is true before the loop, when no letter has been met and every slot holds 0. Each drop keeps it true. So at the end the tray holds the count of every letter.

For cabbage the tray has 26 slots. To ask it about one letter, go in by that letter's place: counts[place(of: "b")] is 2.

The slots are in the order of the alphabet. So a walk along the tray meets the letters in order, and step 4 turns each place back into its letter:

Swift
/// The letters `word` uses, each once, in the order of the alphabet.
func lettersUsed(_ word: String) -> String {
    let counts = letterCounts(word)
    var used = ""
    for place in counts.indices {                // walk the tray from slot 0
        if counts[place] > 0 {
            used.append(letter(at: place))       // a place, back into its letter
        }
    }
    return used
}

For cabbage this gives abceg.

Every ! in this lesson rests on a promise. The shape's is that the word holds only the lowercase letters a to z. When a text may hold anything, step 3's careful place goes in the loop, and a tile with no place has no slot:

Swift
/// How many times each lowercase letter is in `text`. Every other character is skipped.
func letterCounts(in text: String) -> [Int] {
    var counts = Array(repeating: 0, count: 26)
    for character in text {
        if let place = carefulPlace(of: character) {     // nil: not a to z, so no slot
            counts[place] += 1
        }
    }
    return counts
}

For Dad, a cab! the first four slots are [3, 1, 1, 1]. The capital D, the comma, the spaces and the exclamation mark are not counted.

This step has six problems: one missing line of the shape, the shape from nothing, the last two columns of the table in "Watch it run", a mend, and these two uses.

What goes wrong

Reading the back when you wanted the face. The back of "7" is 55, and its face is worth 7. asciiValue is for a letter's place, and wholeNumberValue is for a digit's value.

Subtracting before Int(…). Int(number - 97) subtracts in UInt8, and for any tile that comes before a, such as a capital, a digit or a space, the program stops. Written Int(number) - 97, a capital A gives -32, which the careful place turns away.

! with no promise. asciiValue is nil for é, and wholeNumberValue is nil for q. With no promise of lowercase letters, or of digits, open the optional with if let.

A tray that does not fit. Take 96 off where 97 was meant, and a, b and c land in slots [1, 2, 3]: every letter is one slot late. Make 25 slots where 26 were meant, and the last is slot 24. Either way there is no slot for z, and the program stops. If you forget the 97, Character("a").asciiValue will tell you.

= 1 where += 1 was meant. That marks a slot as used and forgets how many times: for abba the first two slots come out as [1, 1], where they should be [2, 2].

Trusting isNumber with any text. It is true for ½, whose wholeNumberValue is nil. For the ten digits, ask isASCII as well.

Forgetting the ten. Without * 10, the digits of 120 add up to 3.

Say it back

1

Why can you not add 1 to the character "7"?

Show the answerHide the answer

It is a character, not a number: a tile with a seven on its face. A tile has to be turned into a number before any arithmetic.

2

Which property gives a digit's value, and what does it give for a letter?

Show the answerHide the answer

wholeNumberValue. It is an Int?: 7 for "7", and nil for a letter.

3

What is the type of asciiValue, and what does each half of that type make you do?

Show the answerHide the answer

UInt8?. The ? makes you open it: with ! when the problem promises lowercase letters, and with if let when it does not. The UInt8 makes you write Int(…) before you subtract, because it cannot go below zero.

4

How do you get a lowercase letter's place, and how do you get the letter back?

Show the answerHide the answer

Int(letter.asciiValue!) - 97 is the place. Character(UnicodeScalar(UInt8(97 + place))) is the letter.

5

How do you get the characters of 120, and how do you read them back into a number?

Show the answerHide the answer

Array(String(120)). To read them back, start at 0 and take the digits from the left: number = number * 10 + digit.wholeNumberValue!.

6

How many slots has the tray, and which slot does a letter go in?

Show the answerHide the answer

26, made with Array(repeating: 0, count: 26). A letter goes in the slot of its place, and counts[place] += 1 drops it there.

7

Why did the seven say fifty-five when Harper turned it over?

Show the answerHide the answer

It was the character "7", a tile. The back of a tile is its asciiValue, and for "7" that is 55. What the tile is worth is on its face: wholeNumberValue, which is 7. A character is never a number. It carries one on its back and sometimes one on its face, and you ask for the one you mean.

Practise

These are this lesson's problems in the Orithms app, in the order they come.

ProblemLevel
1Digit, letter or otherEasy
2Keep the letters and the digitsEasy
3A half is not a digitEasy
4What a digit is worthEasy
5Add up the digits in a textEasy
6A letter's place in the alphabetEasy
7A capital stops the programEasy
8The letter for a placeEasy
9The first letters of the alphabetEasy
10The characters of a numberEasy
11The digits of a number, as numbersEasy
12A number from its digit charactersEasy
13The number after each digitEasy
14A hundred and twenty comes out as threeEasy
15A number with commas in itEasy
16Drop each letter in its slotEasy
17Count each letter of a wordEasy
18Which slot, and how many now?Easy
19Two of each, counted onceEasy
20The letters a word uses, in orderEasy
21Count the letters of a sentenceEasy

These problems are done in the Orithms Mac app.

Every piece of code and every number in a lesson comes from a file that was compiled and run.