Group UI update LogicTogether

@IBAction func buttonPressed(_ sender: AnyObject) {
    lightOn = !lightOn
    updateUI()
}
 
func updateUI() {
  if lightOn {
    view.backgroundColor = .white
  } else {
    view.backgroundColor = .black
  }
}

This is a small change for a small app. You will see this pattern persist throughout this book, and you will find it much easier to debug interface issues if the code that updates the view is all contained in a single method.

Excerpt From: Apple Education. “App Development with Swift.” Apple Inc. - Education, 2017. iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=1219117996

Strings

multiline string literals

If your string literal needs to be multiple lines, simply surround your set of characters with three double quotation marks """. In its multiline form, the string literal includes all of the lines between its opening and closing quotes. The string begins on the first line after the opening quotes and ends on the line before the closing quotes.  

let joke = """
  Q: Why did the chicken cross the road?
  A: To get to the other side!
  """
print(joke)
Console Output:
Q: Why did the chicken cross the road?
A: To get to the other side!

The whitespace before the closing quotes (""") tells Swift what whitespace to ignore before all of the other lines. Even though both lines of your string literal included whitespace at the beginning, that indentation was stripped off when you printed your string literal since your final three double quotation marks were indented equally as far.”

Excerpt From: Apple Education. “App Development with Swift.” Apple Inc. - Education, 2017. iBooks. https://itunes.apple.com/au/book/app-development-with-swift/id1219117996?mt=11

Escapes

You can use the escape character with other letters and symbols to produce specific results:

Double quote: \"
Single quote: \'
Backslash: \\
Tab: \t
Carriage return: \r

isEmpty?

var myString = ""
 
if myString.isEmpty {
  print("The string is empty")
}

Single characters are strings by default unless you explicitly declare them to be chars.

Concatenation

with = and += as you would expect

Interpolation / template strings

let name = "Rick"
let age = 30
print("\(name) is \(age) years old") ”

Methods

.lowercased

.hasPrefix

.hasSuffix

.contains

.count

“here are a few useful String properties and methods that you could look up:

startIndex

endIndex

index(before:)

index(after:)

index(_:, offsetBy:)

substring(to:)

substring(from:)

substring(with:)

insert(_:, at:)

insert(contentsOf:, at:)

remove(at:)

removeSubrange(_:)

replaceSubrange(_:, with:)

Swift Functions