Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Swift's Data Types  ›  Lesson

Booleans and Strings

Strings 12 minA Bool is only true or false and conditions must be a real Bool, while a String is copied on assignment and inspected with count, isEmpty and similar properties.

Booleans and Strings

Every Sprout habit has a yes-or-no fact, "done today?", and a piece of text, its name. These are two of Swift's simplest types, and each has one rule that surprises people coming from other languages.

The rule

A Bool is only true or false; a String is text you copy.

Bool has exactly two values, true and false. Conditions in Swift must be a real Bool. A number is never treated as true or false:

var isDoneToday = false
isDoneToday.toggle()           // now true

let streak = 3
if streak { }                  // error: an Int is not a Bool
if streak > 0 { }              // fine, a comparison gives a Bool

String holds text. You can join, measure and inspect it:

var name = "Read"
name += " 20 pages"            // "Read 20 pages"
name.count                     // 13
name.isEmpty                   // false
name.hasPrefix("Read")         // true
name.uppercased()              // "READ 20 PAGES"

Each item in a string is a Character, and count counts characters the way a person sees them, so an emoji with a skin tone counts as one.

Strings are values: assigning one to another name makes an independent copy.

let original = "Walk"
var edited = original
edited += " the dog"
// original is still "Walk"

You cannot write name[0] with a plain number. Swift strings are not simple arrays of fixed-size letters, so use name.first (which may be nil for an empty string) or name.prefix(3) instead.

The shortcut

For a condition, ask "is this already true or false?" If it is a number or a string, compare it to something first. For strings, remember copy on assign: changing one name never changes another.

Showing a habit's state in SproutStep 1 of 4
  1. The done flag

    isDoneToday is already a Bool, so if isDoneToday works directly.

Drills

Answer fast — trust the rule.

quick drill

With let streak = 3, what does if streak { } do?

quick drill

What is "Yoga".count?

quick drill

After let a = "Run", var b = a, b += "!", what is a?

quick drill

Which expression gives a Bool?

Remember

  • A Bool is only true or false; a String is text you copy.
  • Conditions need a real Bool, so compare numbers and strings first.
  • Use count, isEmpty and hasPrefix, not name[0].

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhy the name did not change

In Sprout, the edit screen does var draft = habit.name and the user types a new name into draft. Explain why habit.name does not change until it is saved, and what that tells you about Swift strings.