This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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