项目作者: AJ9

项目描述 :
The supplementary Swift Playground to Swift 101 - Guard Statement
高级语言: Swift
项目地址: git://github.com/AJ9/Swift-101-Guard-Statement.git
创建时间: 2017-05-29T14:26:36Z
项目社区:https://github.com/AJ9/Swift-101-Guard-Statement

开源协议:MIT License

下载


Swift 101 - Guard Statement

The supplementary Swift Playground to Swift 101 - Guard Statement.

Playground source

  1. /*:
  2. # Swift 101 - nil
  3. https://medium.com/pretty-swifty/swift-101-guard-statement-9ff5725d4876
  4. I love working with `guard` statements in my Swift code and you should too, let’s take a closer look…
  5. */
  6. import UIKit
  7. //Baskets in this example are an array of Items.
  8. typealias Item = String
  9. typealias Basket = [Item]
  10. var basket: Basket = []
  11. func addToBasket(item: Item) {
  12. guard basket.count < 5 else {
  13. print("Basket is full, Item: \(item) not added")
  14. return
  15. }
  16. basket.append(item)
  17. print("Item: \(item) added to basket")
  18. }
  19. addToBasket(item: "Apple")
  20. addToBasket(item: "Orange")
  21. addToBasket(item: "Grapes")
  22. addToBasket(item: "Pear")
  23. addToBasket(item: "Banana")
  24. addToBasket(item: "Strawberry") // Will not be added to the basket as it's already full
  25. // How to avoid silly divide by zero errors
  26. func divide(lhs: Int, rhs: Int) {
  27. guard rhs > 0 else {
  28. print("Without this guard statement, you would be in a pickle")
  29. return
  30. }
  31. let result = lhs / rhs
  32. print("Result: \(result)")
  33. }
  34. divide(lhs: 10, rhs: 0)
  35. divide(lhs: 10, rhs: 2)
  36. // Using guards as super charged if-let statements
  37. //Uncomment the line below to see what happens when an input value is optional
  38. let input: Any? = nil
  39. //Uncomment the line below to see what happens when an input value is not optional
  40. //let input: Any? = 1
  41. func guardIfLetExample(optionalValue: Any?) {
  42. guard let unwrappedValue = optionalValue else {
  43. print("That optional value was nil")
  44. return
  45. }
  46. print("You can now use unwrappedValue safe in the knowledge that it will never be nil. It was \(unwrappedValue)")
  47. }
  48. guardIfLetExample(optionalValue: input)
  49. // A real world example
  50. var favouriteColour: UIColor? //Because not everyone has a favourite (GB) colour (also GB) you know! Yes, I tend to avoid those people too...
  51. func printColour(_ colour: UIColor?) {
  52. guard let unwrappedColour = colour else {
  53. print("Sorry, the colour you provided was nil")
  54. return
  55. }
  56. print(unwrappedColour) //unwrappedColour is not nil!
  57. }
  58. printColour(favouriteColour)