Swift is technically a C-like language, but as you’ve seen it has a number of features that really make it stand out from the pack. Please don’t worry if you read this chapter and thought, “you know, that just makes no sense” – that’s OK. In fact, it’s perfect normal. Some features, not least optionals, take a good long time to sink in, and you’ll have lots more practice with them as the series progresses.
This was a big chapter with lots of ground covered, so your head might be spinning a bit. If you find something in the list below that you don’t remember, just flick back and re-read. Don’t worry, though: all these things will be covered again in future tutorials, so you’ll have more than enough chance to learn!
let
where possible, rather than variable using var
. Xcode even warns you if you get this wrong.+
, -
, *
, and /
, and compare with >
, <
, and ==
."Your name is \(name)"
will put the value of name
directly into the string.names[4]
. These positions count from zero.person["month"]
.if person == "hater"
, let you take some action depending on the state of your program. You can combine multiple conditions together using &&
.for i in 1...10
, which counts from 1 up to 10 inclusive, for song in songs
, which loops every item item in the songs
array, and also while true
, which causes the loop to go around forever until you exit.continue
to stop the current run of the loop and continue from the next item – it effectively jumps back to the top of the loop and carries on.break
to exit a loop entirely.switch/case
blocks is a good way to execute lots of different code depending on a value. You can use ranges, e.g. 2...3
, but you must always cover every possible value. You can provide a default
case to mean “anything not already matched.”nil
, meaning “no value yet.” (This is the most confusing thing in Swift, and takes some getting used to.)if let
.thingA?.thingB?.thingC = "meh"
will do nothing if either thingA
, thingB
, or thingC
are nil
.??
, lets you provide a default value if an optional is empty. rainy
, cloudy
, and sunny
. Swift lets you add extra values to its enums, to track things like “how cloudy is it?”willSet
and didSet
observers to properties, which means you can ask for code to be run when that property changes.A
and Swift thinks you’re working with an object of type B
, you can use as?
typecasting to tell Swift what it really has. You can use as!
instead, but again your app will crash if you’re wrong.Phew! That’s a lot, but again: all those things will be covered again in more detail in upcoming tutorials – this was just a primer.
SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.