Advertisement
Guest User

Untitled

a guest
Jul 31st, 2015
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. //: Playground - noun: a place where people can play
  2.  
  3. import Foundation
  4.  
  5. let ns = [1,2,3,4,5]
  6.  
  7. // MARK: filter
  8.  
  9. var res1: [Int] = []
  10. for n in ns {
  11. if n % 2 == 0 {
  12. res1.append(n)
  13. }
  14. }
  15. res1 // [2,4]
  16.  
  17. let res2 = ns.filter { $0 % 2 == 0 } // [2,4]
  18.  
  19. // MARK: map
  20.  
  21. var res3: [Int] = []
  22. for n in ns {
  23. res3.append(n * 2)
  24. }
  25. res3 // [2,4,6,8,10]
  26.  
  27. let res4 = ns.map { $0 * 2 } // [2,4,6,8,10]
  28.  
  29. // MARK: flatMap
  30.  
  31. let cs = ["A,B,C", "D,E", "F"]
  32. let res5 = cs.map { $0.componentsSeparatedByString(",") }
  33. res5
  34. let res6 = cs.flatMap { $0.componentsSeparatedByString(",") }
  35. res6
  36.  
  37. func toInt(value: String) -> Int? {
  38. return value.toInt()
  39. }
  40.  
  41. let one: String? = "1"
  42.  
  43. let mapOne = one.map { toInt($0) }
  44. println(mapOne) // => Optional(Optional(1))
  45.  
  46. let flatMapOne = one.flatMap { toInt($0) }
  47. println(flatMapOne) // => Optional(1)
  48.  
  49. // このようにflatMapはmapとよく似ていますが、
  50. // 最初のArrayと要素数が変わったArrayが返ったり、多重のOptionalを避けられたりといった特徴があります。
  51.  
  52. // MARK: reduce
  53.  
  54. var res7 = 0
  55. for n in ns {
  56. res7 += n
  57. }
  58. res7 // 15
  59.  
  60. ns.reduce(0, combine: +) // 15
  61.  
  62. // MARK: sample
  63.  
  64. func fizzbuzz(size: Int) -> [String] {
  65. func exec(n: Int) -> String {
  66. if n % 15 == 0 {
  67. return "FizzBuzz"
  68. } else if n % 5 == 0 {
  69. return "Buzz"
  70. } else if n % 3 == 0 {
  71. return "Fizz"
  72. } else {
  73. return String(n)
  74. }
  75. }
  76.  
  77. return Array(1...size).map { exec($0) }
  78. }
  79.  
  80. let sum = fizzbuzz(40).map({ $0.toInt() }).reduce(0) {
  81. if let i = $1 {
  82. return $0 + i
  83. } else {
  84. return $0
  85. }
  86. }
  87. sum // 412
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement