Created By: Debasis Das (15-May-2017)
In this post we will dive into Swift collection type array and see how it works and then we will apply map, reduce and filter on different arrays and check the corresponding output and behavior
Create an empty array
var array1 = [Int]()
print("is Array1 empty = \(array1.isEmpty)")
//is Array1 empty = true
//Lets append a few elements
array1.append(10)
array1.append(20)
print(array1)
//[10, 20]
Creating an Int array with repeated values
let array2 = [Int](repeating: 2, count: 5)
print(array2)
//[2, 2, 2, 2, 2]
Creating a Float array with repeated values
let array3 = [Float](repeatElement(2.3, count: 5))
print(array3)
//[2.29999995, 2.29999995, 2.29999995, 2.29999995, 2.29999995]
Lets add Two arrays
let array4 = [1,2]
let array5 = [3,4]
let array6 = array4 + array5
print(array6)
//[1, 2, 3, 4]
Accessing and modifying an Array
var monthArray = ["Jan","Feb"]
print ("is month array empty = \(monthArray.isEmpty)")
//is month array empty = false
monthArray += ["Apr","May"]
print(monthArray.first)
//Optional("Jan")
print(monthArray[0])
//Jan
monthArray[0] = "January"
print(monthArray[0])
//January
//Enumerating over an array
for (index, value ) in monthArray.enumerated(){
print("index = \(index) & value = \(value)")
}
/*
index = 0 & value = January
index = 1 & value = Feb
index = 2 & value = Apr
index = 3 & value = May
*/
Array copies
Each array has an independent value that includes the values of all of its elements. For simple types such as integers and other structures, this means that when we change a value in one array, the value of that element does not change in any copies of the array
var array7 = [1,2,3,4,5]
var array8 = array7
array7[0] = 100
print(array7) //[100, 2, 3, 4, 5]
print(array8) //[1, 2, 3, 4, 5] , The first element is still 1 and not 100
Creating an array using Array Initializers
let array9 = Array(1...7)
print(array9)
//[1, 2, 3, 4, 5, 6, 7]
let array10 = Array(1..<7)
print(array10)
//[1, 2, 3, 4, 5, 6]
Creating an array using array literal
let daysArray = ["Monday","Tuesday","Wednesday"]
init(repeating:count:)
Creates a new array containing the specified number of a single, repeated value.
let attendance = Array(repeating: "P", count: 7)
print(attendance)
//["P", "P", "P", "P", "P", "P", "P"]
array count and array capacity
var numbers = [10, 20, 30, 40, 50]
print(numbers.count) //5
print(numbers.capacity) //5
numbers.append(contentsOf: stride(from: 60, through: 100, by: 5))
print(numbers) //[10, 20, 30, 40, 50, 60, 65, 70, 75, 80, 85, 90, 95, 100]
print(numbers.count) //14
print(numbers.capacity) //20
Debug description
print(daysArray.debugDescription) //["Monday", "Tuesday", "Wednesday"]
print(daysArray.description) //["Monday", "Tuesday", "Wednesday"]
first
var array14 = [6,11,15,65,89,12]
var firstMultipleOfFive = array14.first { (num:Int) -> Bool in
return num % 5 == 0
}
print (firstMultipleOfFive) //Optional(15)
print(firstMultipleOfFive.customMirror.subjectType) //Optional Int
Using Map – More on maps in subsequent examples
let array15 = [1,2,3,4,5,6]
let squaredNumbers = array15.map { (num:Int) -> Int in
return num * num
}
print(squaredNumbers) //[1, 4, 9, 16, 25, 36]
let squaredNumbersAsString = array15.map { (num:Int) -> String in
return "\(num * num)"
}
print(squaredNumbersAsString) //["1", "4", "9", "16", "25", "36"]
print(squaredNumbers.max()) //Optional(36)
print(squaredNumbers.min()) //Optional(1)
Array Partition
var array16 = [Int]()
array16 += 1...10
let idx = array16.partition { (num:Int) -> Bool in
num % 2 == 0
}
print (array16[0..<idx]) //[1, 9, 3, 7, 5]
print (array16[idx..<array16.endIndex]) //[6, 4, 8, 2, 10]
Maps, filter and reduce
- map returns an Array containing results of applying a transform to each item.
- filter returns an Array containing only those items that match an include condition.
- reduce returns a single value calculated by calling a combine closure for each item with an initial value.
Map
Map can be used to loop over a collection and apply the same operation to each element in the collection
var array1 = [1,2,3,4,5,6,7,8]
//long form map
var array2 = array1.map { (num:Int) -> Int in
num * num
}
print(array2) //[1, 4, 9, 16, 25, 36, 49, 64]
//short form map
var array3 = array1.map {
$0 * $0
}
print(array3) //[1, 4, 9, 16, 25, 36, 49, 64]
var days = ["Mon","Tues","Wed"]
var daysUpper = days.map { (day:String) -> String in
return day.uppercased()
}
print(daysUpper)//["MON", "TUES", "WED"]
var dates = [NSDate(),NSDate(timeIntervalSince1970: 0)]
var formattedDates = dates.map { (date:NSDate) -> String in
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
let dateString = dateFormatter.string(from: date as Date)
return dateString
}
print(formattedDates) //["5/10/17", "12/31/69"]
Filter
Filter can be used to loop over a collection and return an array containing those elements that match the condition
var array4 = [1,2,3,4,5,6,7,8]
//Filtering the even numbers from an Int Array
var array5 = array4.filter { (num:Int) -> Bool in
return num % 2 == 0
}
print(array5) //[2, 4, 6, 8]
//Filter values greater than certain value in an Array
var array6 = array4.filter { (num:Int) -> Bool in
return num > 3
}
print(array6) //4, 5, 6, 7, 8]
Reduce
reduce can be used to combine all items in a collection to create a single new value.
let array7 = [1.0,3.2,4.5,76.8]
let total = array7.reduce(0) { (x:Double, y:Double) -> Double in
return x+y
}
print(total) //85.5
let newTotal = array7.reduce(100) { (x:Double, y:Double) -> Double in
return x+y
}
print(newTotal) //185.5
//Combining Strings using reduce
let array8 = ["a","b","c","d"]
let concatArray = array8.reduce("") { (x:String, y:String) -> String in
return x+" "+y
}
print(concatArray) // a b c d
Flat Map
let array9 = [[1,2,3],[4,5],[6,7,8]]
let array10 = array9.flatMap {
$0
}
print(array10) //[1, 2, 3, 4, 5, 6, 7, 8]
let array11 = array9.flatMap { (intArray) -> [Int] in
intArray.filter({ (num:Int) -> Bool in
return num%2 == 0
})
}
print(array11) //[2, 4, 6, 8]
Chaining
We can chain methods (filter, map etc)
let array12 = [1,2,3,4,5,6,7,8]
let array13 = array12.filter { (num:Int) -> Bool in
num%2==0}.map { (num:Int) -> Int in
num * num
}
print(array13) //[4, 16, 36, 64]
//In the above code we are filtering the array to find out only the even numbers followed by doing a square on each indvidual even number and finally returning the array