compactmap
///lets say we have array of string which contains Int value but we are not sure about that
///all the elements can convert into int because we some element can't be int
var array = ["3", "data", "2", "5", "23", "hello"]
var simpleMapResult: [Int?] = array.map { elment in
return Int(elment)
}
print("The original array => ")
print(array)
print("\nAfter maping through we'll see the result is option int array =>")
print(simpleMapResult)
///Next task is make them no-optional and remove nil
var simpleMapRemovedNil: [Int?] = simpleMapResult.filter { element in
return element != nil
}
print("\nNow we have array of int which does not have nil value")
print(simpleMapRemovedNil)
//Now make them non-optional
var simpleMapNonOptional: [Int] = simpleMapRemovedNil.map { element in
return element!
}
print("\nNow we have array of non-optional int")
print(simpleMapNonOptional)
/// not the simple approch is compactMap
var compactMapNonOptional: [Int] = array.compactMap { elment in
return Int(elment)
}
print("\nCompact map output")
print(compactMapNonOptional)
/* Output is
The original array =>
["3", "data", "2", "5", "23", "hello"]
After maping through we'll see the result is option int array =>
[Optional(3), nil, Optional(2), Optional(5), Optional(23), nil]
Now we have array of int which does not have nil value
[Optional(3), Optional(2), Optional(5), Optional(23)]
Now we have array of non-optional int
[3, 2, 5, 23]
Compact map output
[3, 2, 5, 23]
*/
Developer101