Skip to content

Instantly share code, notes, and snippets.

@MariuszWisniewski
Last active February 15, 2016 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MariuszWisniewski/ef5744b6d39b87e0f32f to your computer and use it in GitHub Desktop.
Save MariuszWisniewski/ef5744b6d39b87e0f32f to your computer and use it in GitHub Desktop.
class Author {
var name = ""
init(name: String) {
self.name = name
}
}
class Book {
var author : Author? = nil
func setAuthor(author: Author) {
self.author = author
print("Author set to \(author.name)")
}
}
let foo : Book? = Book()
let bar : Author? = Author(name: "Bob")
func letIndentationHell(foo: Book?, bar: Author?) {
if let book = foo {
if let author = bar {
book.setAuthor(author)
}
}
}
func multipleBind(foo: Book?, bar: Author?) {
if let book = foo, let author = bar {
book.setAuthor(author)
}
}
func objcStyle(foo: Book?, bar: Author?) {
if (foo == nil || bar == nil) {
return
}
let book = foo!
let author = bar!
book.setAuthor(author)
// or force unwrap both directly with
// foo!.setAuthor(bar!)
}
func swiftGuardStyle(foo: Book?, bar: Author?) {
guard let book = foo, author = bar else {
return
}
book.setAuthor(author)
}
func swiftGuardStyle2(book: Book?, author: Author?) {
guard let book = book, author = author else {
return
}
book.setAuthor(author)
}
func swiftGuardStyleWhere(book: Book?, author: Author?, rating: Int) {
guard rating > 4, let book = book, author = author where author.name == "Bob" else {
return
}
book.setAuthor(author)
}
letIndentationHell(foo, bar: bar)
multipleBind(foo, bar: bar)
objcStyle(foo, bar: bar)
swiftGuardStyle(foo, bar: bar)
swiftGuardStyle2(foo, author: bar)
swiftGuardStyleWhere(foo, author: bar, rating: 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment