Sunday, November 13, 2016

Swift helper methods for array, dictionary and set

Quite ofter it is needed to loop through each element in an array or dictionary to do certain operation on each element. Swift provides few helper methods to make the operation simple.

The array is used to demo these helper methods

1. sorted, sorted(by:)
Sort an array elements based on default or custom comparison logic. This is a swift standard library function.

Sample sort by default order
        let values = [2, -24, 5, 7]

        let sortedArray = values.sorted()
        print(sortedArray)
            //[-24, 2, 5, 7]

Sample sort by custom comparison

      let sortedArray2 = values.sorted (by: { (a: Int, b: Int) -> Bool in

              return a*a < b*b
            })
        print(sortedArray2)

       //[2, 5, 7, -24]

As the parameter is defined by sorted(by:) function, so the type information can be omitted as 
      let sortedArray3 = values.sorted (by: { a, b in
              return a*a < b*b
            })
        print(sortedArray3)

As the block body only as a single expression, the return clause can also be omitted
 let sortedArray4 = values.sorted (by: { a, b in
              a*a < b*b
            })
        print(sortedArray4)

In addition, the parameter can also referred by their index as $0, $1, $2 from the parameter list, so the expression can be simplified as 
 let sortedArray5 = values.sorted (by: 
              { $0*$0 < $1*$1
            })
        print(sortedArray5)

2. map
For each item in the array, do some operation on it and then return a new array with the processed items.
   let values = [2, -24, 5, 7]
   let square = values.map ({ (item:Int) -> Int in
         return item * item
        })

   print(square)   
   //output
   //[4, 576, 25, 49]

as the function only as a single unnamed block argument, the (), and parameter type information can be simplified as
       let square2 = values.map{ $0 * $0}

        print(square2) 


3. filter
Loop through the collection and return a new collection with the satisfied elements, the returned element type is same as original type

To get the positive even number from the above array
        let filtered = values.filter { (item: Int) -> Bool in
            let i = item % 2
            return i == 0 && item > 0
            }
            
        print((filtered))
        
Simplified express looks like below
        let filtered2 = values.filter {
            let i = $0 % 2
            return i == 0 && $0 > 0
            }
            
        print((filtered2))

4. reduce
reduce can be used to go through each element and accumulate the result from previous element, for example, to calculate the sum
The first parameter is the initial value, which does not need to be the same type as collection element 
        let output = values.reduce("the array is: ", {(ret, item: Int) in
            return ret + (String(item)) })
        print(output)
        //the array is: 2-2457

Simplified express is
        let output2 = values.reduce("the array is: "){$0 + (String($1)) }
        print(output2)

No comments:

Post a Comment