Swift-Closures

  https://www.weheartswift.com/closures/

  • Currying  柯里化
    • e.g.1
    • //返回值为  参数为Int返回值为Int的闭包
      func addTo(adder: Int) -> Int -> Int {
           return {
                num in 
                return num + adder
                 }
      }
      
      let addTwo = addTo(2) 
      /* 
      addTwo = (num: Int) -> Int {
          return num + 2
      }
      */
      
      let result =addTwo(6)

       

    • e.g.2
    • //$0 闭包默认的第一个参数
      func greaterThan(comparer:Int) -> Int -> Bool {
              return {$0 > comparer}
      }
      
      let greaterThan10 = greaterThan(10)
      
      greaterThan10(12)
      greaterThan10(9)

       

    • e.g.3
    • func makeIterator(from start: Int, step: Int) -> () -> Int {
          var i = start
          return {
              let currentValue = i
              i += step
              return currentValue
          }
      }
      
      var iterator = makeIterator(from: 1, step: 1)
      
      iterator() // 1
      iterator() // 2
      iterator() // 3
      
      var anotherIterator = makeIterator(from: 1, step: 3)
      
      anotherIterator() // 1
      anotherIterator() // 4
      anotherIterator() // 7
      anotherIterator() // 10

       

  • Closures in Swift (原作者的警告⚠️:When you have a new hammer everything starts to look like a nail.)
    •   Array: Sort, Map, Filter, Reduce
      • Sort
      • var array = [3, 4, 5]
        array.sort(by: >) 
        
        // > is defined as function
        // sort does not return a new array
        // the original array has been changed

         

      • Reduce
      • sum = array.reduce(0, {$0 + $1})
        
        // or 
        
        sum = array.reduce(0, +) // operators are methods in Swift

         

      • Map
      • let array = [2, 3, 4]
        
        /// result is  [3, 4, 5]
        
        array.map{ $0 + 1}

         

      • Filter
      • let array = [2, 3, 4]
        let newArray = array.filter({ $0 > 3})
        //newArray = [4]
posted @ 2018-02-22 15:27  ShellHan  阅读(143)  评论(0编辑  收藏  举报