Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: Playground - noun: a place where people can play
- import Foundation
- let ns = [1,2,3,4,5]
- // MARK: filter
- var res1: [Int] = []
- for n in ns {
- if n % 2 == 0 {
- res1.append(n)
- }
- }
- res1 // [2,4]
- let res2 = ns.filter { $0 % 2 == 0 } // [2,4]
- // MARK: map
- var res3: [Int] = []
- for n in ns {
- res3.append(n * 2)
- }
- res3 // [2,4,6,8,10]
- let res4 = ns.map { $0 * 2 } // [2,4,6,8,10]
- // MARK: flatMap
- let cs = ["A,B,C", "D,E", "F"]
- let res5 = cs.map { $0.componentsSeparatedByString(",") }
- res5
- let res6 = cs.flatMap { $0.componentsSeparatedByString(",") }
- res6
- func toInt(value: String) -> Int? {
- return value.toInt()
- }
- let one: String? = "1"
- let mapOne = one.map { toInt($0) }
- println(mapOne) // => Optional(Optional(1))
- let flatMapOne = one.flatMap { toInt($0) }
- println(flatMapOne) // => Optional(1)
- // このようにflatMapはmapとよく似ていますが、
- // 最初のArrayと要素数が変わったArrayが返ったり、多重のOptionalを避けられたりといった特徴があります。
- // MARK: reduce
- var res7 = 0
- for n in ns {
- res7 += n
- }
- res7 // 15
- ns.reduce(0, combine: +) // 15
- // MARK: sample
- func fizzbuzz(size: Int) -> [String] {
- func exec(n: Int) -> String {
- if n % 15 == 0 {
- return "FizzBuzz"
- } else if n % 5 == 0 {
- return "Buzz"
- } else if n % 3 == 0 {
- return "Fizz"
- } else {
- return String(n)
- }
- }
- return Array(1...size).map { exec($0) }
- }
- let sum = fizzbuzz(40).map({ $0.toInt() }).reduce(0) {
- if let i = $1 {
- return $0 + i
- } else {
- return $0
- }
- }
- sum // 412
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement