Since last posts about using let
and guard
, Swift 3 came out and changed a few things here and there. Let’s see what’s new!
Let’s start from the beginning - the basics are still the same. So still, please don’t do:
if let x = x {
if let y = y {
if let z = z {
print("x = \(x), y = \(y), z = \(z)")
x * y * z * 3
}
}
}
or
func objcStyle(foo: Int?, bar: Int?) {
if (foo == nil || bar == nil) {
return
}
let a = foo!
let b = bar!
a.advanced(by: b)
// or force unwrap both directly with
// a!.advanceBy(by: b)
}
and instead do these two:
if let x = x, let y = y, let z = z {
print("x = \(x), y = \(y), z = \(z)")
x * y * z * 3
}
and
func swiftGuardStyle(foo: Int?, bar: Int?) {
guard let a = foo, let b = bar else {
return
}
a.advanced(by: b)
}
In short - use Swift like it was meant to be, not like you would be writing Obj-C, jus using Swift syntax.
One important change is using where
clause. For full summary of changes, you can visit Swift Evolution.
In short - now, this change makes each clause in if
statement separate from each other and limits clauses to a single item. To make it easier to understand, take a look at Swift 2 and 3 examples below:
// SWIFT 2
func swiftGuardStyleWhere(book: Book?, author: Author?, rating: Int) {
guard rating > 4, let book = book, author = author where author == "Bob" else {
return
}
// will only execute if book and author are non nil
// and when author's name is "Bob"
// and when rating is > 4
doSomething()
}
func swiftGuardStyleWhere(book: Book?, author: Author?, rating: Int) {
guard rating > 4, let book = book, let author = author, author == "Bob" else {
return
}
// will only execute if book and author are non nil
// and when author's name is "Bob"
// and when rating is > 4
}
What’s different?
- Because each clause is now separated by
,
, you need to typelet
in each clause – before all confitional binding statements (it doesn’t propagate) where
keyword is removed and replaced by,
– each sub-clause of theif
statement is now an independent boolean test
That’s really it – when it comes to topics covered by previous two blog posts, nothing else changed. Make sure to get rid of where
clause from your if
statements and repeat let
for every sub-clause and you will be fine!