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
Boolis only true or false; aStringis 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 BoolString 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.
The done flag
isDoneTodayis already aBool, soif isDoneTodayworks directly.
Drills
Answer fast — trust the rule.
With let streak = 3, what does if streak { } do?
What is "Yoga".count?
After let a = "Run", var b = a, b += "!", what is a?
Which expression gives a Bool?
Remember
- A
Boolis only true or false; aStringis text you copy. - Conditions need a real
Bool, so compare numbers and strings first. - Use
count,isEmptyandhasPrefix, notname[0].
