[{"content":"So, it seems that this is the end of the way for Swifty Collections! We learned that there are some functions called Higher Order Functions and their difference with normal ones is that they deal with other functions, either as a parameter or as a return type.\nAlso we learned that Swift provides three primary collection types (arrays, sets, and dictionaries) for storing collections of values.\nThen there were our lovely trio: * .map, .filter, .reduce * .\nHere we have a summary of what they are and a simple , Swifty example of them!\n.map, .compactMap, .flatMap : .map :  The whole idea is about mapping collection elements , do something on them and then return the same-sized array of them ! Complexity? O(n)\n import Foundation var array = [2, 3, 4, 5] // 1. Just pass a closure as parameter in .map function and that's that ! let newArray_ModernStyle = array.map { (element) -\u0026gt; Int in element * element } print(newArray_ModernStyle) // Result -\u0026gt; [4, 9, 16, 25] //2. It's what swift offers to help us live better :) $0 acts as (element) in _ModernStyle's map closure. let newArray_SwiftyWay = array.map { $0 * $0 } print(newArray_SwiftyWay) // Result -\u0026gt; [4, 9, 16, 25] .compactMap :  .compactMap is almost the same as .map with one difference ; .compactMap discards all of nil results so the newArray contains only valid transformed elements. And here we don\u0026rsquo;t expect the same-sized array to be returned . .compactMap returns an array containing the non-nil results of calling the given transformation with each element of this sequence ! Complexity? O(m +n) [m is the length of the result]\n import Foundation var array: [String] = [\u0026quot;2\u0026quot;, \u0026quot;3\u0026quot;, \u0026quot;Four\u0026quot;, \u0026quot;Roronoa Zoro\u0026quot;] let newArray_ModernStyle = array.compactMap { (element) -\u0026gt; Int? in Int(element) } print(newArray_ModernStyle) // Result -\u0026gt; [2, 3] let newArray_SwiftyWay = array.compactMap { Int($0) } print(newArray_SwiftyWay) // Result -\u0026gt; [2, 3] Wait wait \u0026hellip; Who was Roronoa Zoro? You mean you hadn\u0026rsquo;t read the full article?\n*Psst \u0026hellip; check out switycode.com/.map :) *\n.flatMap :  In Swift 4.1+ .flatMap is used only to help you flattening a nested collection into a single array. Complexity? Complexity? O(m +n) [m is the length of the result]\n import Foundation var array: Array\u0026lt;[Int]\u0026gt; = [[1], [2, 3, 4, 5], [6, 7]] let newArray_ModernStyle = array.flatMap { (element) -\u0026gt; [Int] in element } print(newArray_ModernStyle) let newArray_SwiftyWay: [Int] = array.flatMap { $0 } print(newArray_SwiftyWay)  **✨ As I\u0026rsquo;ve mentioned above, you can read the full, detailed article at switycode.com/.map **\n .filter :  .filter returns a new array , with elements which are ok with the predicate (~given logic) declared by the closure; Keep in mind that returned array has the same order as the given array. Complexity? O(n)\n import Foundation var array = [10, 7, 1, 4, 0, -2, 20] let newArray = array.filter { (element) -\u0026gt; Bool in element \u0026lt; 5 } print(newArray) let newArraySwifty = array.filter( { $0 \u0026lt; 5 }) print(newArray) // Result -\u0026gt; [1, 4, 0, -2]  **☄️ As you might\u0026rsquo;ve noticed we could use .comapctMap instead of .filter! So why .filter? The answer is in the full article at switycode.com/.filter **\n .reduce : **Although it\u0026rsquo;s unbelievably useful but it is a bit tricky! So I deeply suggest you read the detailed article of this awesome Instance Method at switycode.com/.filter! **\n*There is also a semi-real world example on .map and .reduce + a bit of structs there -with Naruto 🦊 , Dattebayo! *\n.reduce -classic 😂 :  Whenever you felt like combining a collection, you can depend on .reduce! It only needs the collection you wanna combine , a baseValue to start combining with and the way you\u0026rsquo;d like it to combine -passed by a closure. Complexity? O(n)\n import Foundation var array = [1, 2, 3, 4, 5] let combinedValue = array.reduce(0) { (previousResult, currentElement) -\u0026gt; Int in previousResult + currentElement } print(combinedValue) // -\u0026gt; 15 let swiftyCombinedValue = array.reduce(0) { $0 + $1 } print(swiftyCombinedValue) // -\u0026gt; 15 let swiftyCombinedValue_UltimateEdition = array.reduce(0, +) print(swiftyCombinedValue_UltimateEdition) // -\u0026gt; also 15! What'd you expect?! If there is anything you feel uncomfortable with, let me know via alireza@swiftycode.com or Twitter: @swiftycode_com . I\u0026rsquo;d try my best to explain it the way you\u0026rsquo;d understand ;)\n.reduce(into:) -the overloaded bro 🤣 :  By using .reduce(into:) we reduce -or combine- the sequence using the given closure into the initialResult while in .reduce we did create a new value from combined -reduced- elements! Complexity? O(n)\n import Foundation let array = [1, 2, 4, 5] let reduceInto = array.reduce(into: 0) { (previousResult, currentElement) in previousResult += currentElement } print(reduceInto) // -\u0026gt; 12 O\u0026hellip;..K! As I\u0026rsquo;ve mentioned before the next series is Swifty Types: What are named types? . There we\u0026rsquo;ll dive deep in named types to learn about Class, Struct, Enum, Protocol, and etc. in our beloved Swift ! See you soon :)\nThere will also be a single article , Swifty String: What are Strings behind the scene? and there, we\u0026rsquo;ll find another Higher Order Function called .split and lots of interesting things about Strings in Swift!\nFarewell, Swifty Collections -for now \u0026hellip; 🙌🏼\n *Thanks a lot for coming this far and reading the article :) As you may know it was a summary on a series about Higher Order Functions of Swift\u0026rsquo;s Collection , so make sure to read previous articles -if you hadn\u0026rsquo;t already- to completely master this subject -Dattebayo! . Stay Safe , Code Well \u0026amp; Watch Naruto =) *\n If you have any questions, suggestions or etc. feel free to contact me at alireza@swiftycode.com . We can also chat about One Piece ,Macbeth \u0026amp; Naruto beside Swift -kidding- on Twitter at @swiftycode_com .\n ","permalink":"https://swiftycode.com/blog/posts/part-v-farewell-swifty-collections/","summary":"A brief summary on swift collections' functions such as reduce, filter, map and etc.","title":"Part (V) : Farewell , Swifty Collections!"},{"content":"Well, as always , It\u0026rsquo;s simple !\nYeah , although it doesn\u0026rsquo;t seem so but .reduce\u0026rsquo;s functionality is super useful while super simple :)\n.reduce : Imagine you have a collection (e.g. an array) of some elements . It doesn\u0026rsquo;t matter if it is an array of Ints or a set of structs ; What would you do if you wanted to combine its elements? For example you have an array of Ints and you wanna know about their sum (It\u0026rsquo;d be like combining integers by sum operation) !\nvar array = [1, 2, 3, 4, 5] var baseValue = 0 for element in array { baseValue += element } print(baseValue) // -\u0026gt; 15 Wanna know what Swift offers instead of the classic simple for-in loop in our case? *I\u0026rsquo;m honored to introduce you , the .reduce . * As developer.apple.com says, the whole reason of Swift giving birth to .reduce is :\n To return the result of combining the elements of the sequence using the given closure.\n Well, don\u0026rsquo;t bother him -Apple Documentation- he only wants to say that :\n Whenever you felt like combining a collection, you can depend on .reduce! It only needs the collection you wanna combine , a baseValue to start combining with and the way you\u0026rsquo;d like it to combine -passed by a closure.\n Let\u0026rsquo;s help ourselves with .reduce :\nvar array = [1, 2, 3, 4, 5] let combinedValue = array.reduce(0) { (previousResult, currentElement) -\u0026gt; Int in previousResult + currentElement } print(combinedValue) // -\u0026gt; 15 Om\u0026hellip;,well, well, well , well, \u0026hellip; ( for _ in 0\u0026hellip;3 { print(\u0026ldquo;well\u0026rdquo;) } ) although it seems a bit confusing but believe me it\u0026rsquo;s unbelievably easy! Let me explain .\nJust like what we saw in the for loop example above , we need to have a baseValue so that we can start the whole combining thing . Then we should let the .reduce function , to know how we desire our given collection (in this case array) to be combined . The passing closure of our combining logic must have two arguments which they\u0026rsquo;d represent previousResult and the currentElement :\n** previousResult** is the result of combining the given array\u0026rsquo;s elements until now -the currentElement.\n** currentElement** is the \u0026hellip; -do I really need to explain it? :)\nSo, to represent the .reduce function developer.apple.com says :\nfunc reduce\u0026lt;Result\u0026gt;(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -\u0026gt; Result) rethrows -\u0026gt; Result To understand the above declaration you need to have good grasp of Generics in Swift -I\u0026rsquo;ll write about it soon . To translate it in the most simple -careless- way possible for our example here is what we need for now -I know, it\u0026rsquo;s sloppy :\na function to reduce(baseValue: Int, previousResult_AddedTo_currentElement: (Int, Int) -\u0026gt; Int) -\u0026gt; Int So now you know that to combine a Sequence (collection) you need to have a baseValue to start with and a block of code (closure) to apply your desired logic . Like other Instance Methods and Higher Order functions in Swift , there is also a more Swifty way to use .reduce :\nvar array = [1, 2, 3, 4, 5] let swiftyCombinedValue = array.reduce(0) { $0 + $1 } print(swiftyCombinedValue) // -\u0026gt; 15 As you already know $0 is the first and $1 is the second argument of our closure , which in our case (.reduce) $0 refers to previousResult and $1 to the currentElement . Since we wanted to know about the sum of our array , we started with 0 as our initialResult to not to affect our final result.\nTo go through what .reduce is doing generally , step by step, it\u0026rsquo;s like :\n\u0026ldquo;Where do I start? Give me an initialResult -maybe baseValue-\u0026rdquo; .reduce asks,\n\u0026ldquo;Ok you wanted me to combine a collection for you. Then how do I do that?\u0026rdquo;\n\u0026ldquo;Would you mind passing the logic inside my closure , which has to arguments of what\u0026rsquo;s the result of combining previous elements -previousResult- or your given initialResult and which element I\u0026rsquo;m currently on -currentElement.\u0026rdquo;\nThen it iterates through the array by having the result of previous combinations and tries applying the combination logic -passed through the closure- to each element .\nKeep in mind that at the starting point it uses the given initialResult -which we also called baseValue in our example- as the ..result of previous combinations.. .\nAccording to developer.apple.com , .reduce has :\n complexity of O(n), where n is the length of the sequence.\n \u0026hellip; it\u0026rsquo;s obvious because it traverses the whole given sequence for our sake !\nOne more magic! There\u0026rsquo;s also another awesome way to use .reduce and it is Ultimately Swifty!\nBy now we\u0026rsquo;ve understood that .reduce\u0026rsquo;s closure is smart enough to know $0 and $1 are its arguments; As you might have noticed the way we use it is somehow like an operation on its two arguments! What if we could only pass the operator and leave the rest to our smart Swifty closure?\nWell, here it is:\nvar array = [1, 2, 3, 4, 5] let swiftyCombinedValue_UltimateEdition = array.reduce(0, +) print(swiftyCombinedValue_UltimateEdition) .reduce(into:) : Well, to be honest at first .reduce(into:) seemed a bit tricky to myself but after trying to find its differences with the classic .reduce the whole thing was surprisingly easy! So, It\u0026rsquo;s simple :)\nAs you might have already guessed, it\u0026rsquo;s almost the same as classic .reduce! If there were more differences between them, why would they just overload it?\nThe first thing we\u0026rsquo;d notice is the extra into: parameter; It\u0026rsquo;s saying: \u0026hellip;reduce into me! As we\u0026rsquo;ve learned above, .reduce needed a starting point(starting value) called initialResult , here in .reduce(into:) it\u0026rsquo;s somehow the same but there is a bit of a difference in the mechanism.\n By using .reduce(into:) we reduce -or combine- the sequence using the given closure into the initialResult while in .reduce we did create a new value from combined -reduced- elements!\n Let\u0026rsquo;s take a look at their templates:\n// Classic .reduce func reduce\u0026lt;Result\u0026gt;(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -\u0026gt; Result) rethrows -\u0026gt; Result // Overloaded .reduce(into:) func reduce\u0026lt;Result\u0026gt;(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -\u0026gt; ()) rethrows -\u0026gt; Result As the arguments' naming offers, nextPartialResult (.reduce\u0026rsquo;s closure) is named updateAccumulatingResult which suggests the same idea of combining into initialResult instead of returning the combined value through the closure !\nThat\u0026rsquo;s why nextPartialResult (given closure) in .reduce returns the result ,while updateAccumulatingResult in .reduce(into:) returns Void -nothing.\nDid you notice the inout keyword in .reduce(into:) closure? Well, that was the key difference!\n Long story short, inout is used when we need to make the functions' parameters mutable! That means modifying the local variable will also modify the passed-in parameter.\n Riddle solved! Instead of copying the initialResult , .reduce(into:) uses it to add-up combined results into . That\u0026rsquo;s why developer.apple.com says:\n .reduce(into:) is preferred over .reduce for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.\n Let\u0026rsquo;s see an example to help you understand it better (Although it\u0026rsquo;s not the best/most-preferred example but it\u0026rsquo;s useful to compare .reduce an .reduce(into:) :\nlet array = [1, 2, 4, 5] let claasicReduce = array.reduce(0) { (previousResult, currentElement) -\u0026gt; Int in return previousResult + currentElement } print(claasicReduce) // -\u0026gt; 12 let reduceInto = array.reduce(into: 0) { (previousResult, currentElement) in previousResult += currentElement } print(reduceInto) // -\u0026gt; 12  If there is anything you feel uncomfortable with, let me know via alireza@swiftycode.com or Twitter: @swiftycode_com . I\u0026rsquo;d try my best to explain it the way you\u0026rsquo;d understand ;)\n That\u0026rsquo;s all for .reduce! But if you\u0026rsquo;re looking forward to see a semi real-world example of .reduce with structs in Swift you can follow along; *Keep in mind that you must have watched Naruto to understand this example -Just kidding I\u0026rsquo;ll spoil it for you (without affecting the story) 👹. *\nNaruto x .reduce: The .reduce jutsu! I\u0026rsquo;m super happy to see you here -Believe it!\nIf you don\u0026rsquo;t know the 7th Hokage, Naruto, let me tell you what you need to come along.\nNaruto is a lovely character in Naruto Shippuden series who has an amazing ability -jutsu- called Shadow Clones to produce clones of himself. They\u0026rsquo;re copies of him , that once they merge back into him they add all they\u0026rsquo;ve experienced, learned or trained to the main Naruto. Can you guess how does he do merging back part? Yay, it\u0026rsquo;s the .reduce jutsu! (Jutsu ~= Technique)\nEnough talk, let\u0026rsquo;s dive into the code by creating an Struct for Naruto which has four properties :\nclass Naruto { var isClone: Bool var stamina = 100 , powerLevel = 0 , usedStamina: Int init(usedStamina: Int, isClone: Bool = true) { self.usedStamina = usedStamina self.isClone = isClone stamina -= usedStamina } } For now, the main Naruto hast 100 stamina and power level of 0; There is also isClone and used stamina to keep track of how much energy a clone used , and to see wether it is a clone or the actual Naruto -I know that this part is not a best practice .\nOk, let\u0026rsquo;s create the real Naruto and ask him to create his shadow clones to get trained!\n// Here we have the Real Hero -Naruto . Dattebayo! var realNaruto = Naruto(usedStamina: 0, isClone: false) // Ok, Shadow Clone Jutsu ... Poof! var narutoClonesArray = [ realNaruto, Naruto(usedStamina: 10), Naruto(usedStamina: 5), Naruto(usedStamina: 15), Naruto(usedStamina: 30) ] By now we have 4 clones of Naruto which they\u0026rsquo;ve already used some stamina.\nNow, let\u0026rsquo;s start training them -Naruto and his clones. As a Sensei -trainer- I\u0026rsquo;d prefer using .map to train each of them equally to gain power level of 20.\n// Well dear Shadow Clones , let's train for Alireza Sensei . var trainedNarutoClones = narutoClonesArray.map { (clone) -\u0026gt; Naruto in clone.powerLevel = 20 return clone } Now that we have an array of trained Naruto and clones it\u0026rsquo;s time to gather up all of the clones so that our dear Naruto can power-up ! *** .reduce Jutsu*** :\n// Time to gather up clones ... realNaruto = trainedNarutoClones.reduce(realNaruto, +) Wow! -probably in a for loop of 0\u0026hellip;10! .\nHow did you add up those Naruto objects? Let me reveal the hidden part of my code :\n// How to add up Naruto's Shadows Clones extension Naruto { static func +(left: Naruto, right: Naruto) -\u0026gt; Naruto { let narutoClone = Naruto(usedStamina: 0) narutoClone.stamina = right.stamina + left.stamina narutoClone.powerLevel = right.powerLevel + left.powerLevel if !right.isClone || !left.isClone { narutoClone.isClone = false } return narutoClone } }  What we\u0026rsquo;ve done is called Operator Overloading ; It\u0026rsquo;s the act of overloading an operator\u0026rsquo;s function so that we can use different argument types! Soon, I\u0026rsquo;ll publish an article on how to make use of operator overloading deeply!\n Curious how much power did Naruto gain and how much stamina did he used? As you might know it\u0026rsquo;s not like print(realNaruto) would give us any information! So here Swift comes to save us :\n//Print detail of Naruto state: extension Naruto: CustomStringConvertible { var description: String { \u0026quot;Current State-\u0026gt; Power Level: \\(powerLevel), Stamina: \\(stamina), Is Clone: \\(isClone)\u0026quot; } } So \u0026hellip; let\u0026rsquo;s print Naruto like a pro :\nprint(realNaruto) // \u0026quot;Current State-\u0026gt; Power Level: 120, Stamina: 540, Is Clone: false\u0026quot;  You might wonder why I\u0026rsquo;ve used Class and not Struct? The answer is something like this : Classes are reference types ! Well, Let me spoil that :) The next series is Swifty Types: What are named types? .\n  *Thanks a lot for coming this far and reading the article :) As you may know it\u0026rsquo;s a series about Higher Order Functions of Swift\u0026rsquo;s Collection , so make sure to read next articles as well as previous one -if you hadn\u0026rsquo;t already- to completely master this subject -Dattebayo! . Stay Safe , Code Well \u0026amp; Watch Naruto =) *\n If you have any questions, suggestions or etc. feel free to contact me at alireza@swiftycode.com . We can also chat about One Piece ,Macbeth \u0026amp; Naruto beside Swift -kidding- on Twitter at @swiftycode_com .\n ","permalink":"https://swiftycode.com/blog/posts/part-iv-reduce/","summary":"Let\u0026rsquo;s learn what is .reduce and .reduce into in Swift\u0026rsquo;s collections and much more about such Higher Order Functions \u0026hellip;","title":"Part (IV) : What is .reduce in Swift?"},{"content":"It\u0026rsquo;s simple! as you already know , .filter is a Higher Order Function for collections in Swift. Just like .map, .filter is also referred as Instance Method .\nWhy do we need .filter?\n.filter : Well, well \u0026hellip; as developer.apple.com says, .filter\u0026rsquo;s job is to :\n Return an array containing, in order, the elements of the sequence that satisfy the given predicate.\n I know that it\u0026rsquo;s somehow hard to understand to make it a little bit readable , we can say that :\n .filter returns a new array , with elements which are ok with the predicate (~given logic) declared by the closure; Keep in mind that returned array has the same order as the given array.\n Behind the scenes , .filter is doing a simple job; It iterates through the whole given array , checks if the given predicate -passed as a closure- applies to the element , returns a Bool indicating the true/false state of the operation for the element; if it the result were true the element would be added to the array we\u0026rsquo;re expecting in return .\nThe only thing we need to know for our daily use is that we can filter an array with .filter by any logic we need and get a new array filtered as we desire !\nHere is the example for .filter :\nimport Foundation var array = [10, 7, 1, 4, 0, -2, 20] let newArray = array.filter { (element) -\u0026gt; Bool in element \u0026lt; 5 } print(newArray) let newArraySwifty = array.filter( { $0 \u0026lt; 5 }) print(newArraySwifty) Can you guess the result ? -\u0026gt; [1, 4, 0, -2]\nThe passed predicate (logic) was to filter our array to have a newArray with only greater than 3 Integers. Wasn\u0026rsquo;t it really simple? the complexity in O(n) , as obvious as it is, because it needs to traverse the whole array once to check the given predicate . Note that here , n is the length -count- of main array.\n.filter or .compactMap , that is the question! Think about the following code :\nimport Foundation var array = [10, 7, 1, 4, 0, -2, 20] let newArray = array.filter { (element) -\u0026gt; Bool in element \u0026lt; 5 } let newArray_compactMap = array.compactMap { (element) -\u0026gt; Int? in if element \u0026lt; 5 { return element } else { return nil } } print(newArray) print(newArray_compactMap) let newArraySwifty = array.filter( { $0 \u0026lt; 5 }) let newArraySwifty_compactMap: [Int] = array.compactMap( { if $0 \u0026lt; 5 { return $0 } else { return nil } }) print(newArray) print(newArray_compactMap) // Result -\u0026gt; [1, 4, 0, -2] It seems that we can achieve our goal by writing few more codes with .compactMap instead of .filter ! So , why did Apple bother creating .filter? It\u0026rsquo;s the tricky part :)\n According to developer.apple.com/.filter and developer.apple.com/ .compactMap while .filter\u0026rsquo;s complexity is O(n) , it is O(m + n) in .compactMap !\n The same issues -as .compactMap- go with .map plus .map isn\u0026rsquo;t able to discard nil resulted elements =)\nHere\u0026rsquo;s where Hamlet comes in and says \u0026ldquo;To be, or not to be, that is the question: Whether \u0026lsquo;tis nobler in the mind to suffer The slings and arrows of outrageous fortune,\u0026quot; \u0026hellip; well , I guess by [The slings and arrows] , he meant misusing .compactMap instead of .filter which will cause us so much pain -I\u0026rsquo;ll assure you it\u0026rsquo;s nothing near noble =))) .\nNext : Part (IV) : What is .reduce in Swift?\n *Thanks a lot for coming this far and reading the article :) As you may know it\u0026rsquo;s a series about Higher Order Functions of Swift\u0026rsquo;s Collection , so make sure to read next articles as well as previous one -if you hadn\u0026rsquo;t already- to completely master this subject . Stay Safe , Code Well \u0026amp; Read Macbeth =) *\n If you have any questions, suggestions or etc. feel free to contact me at alireza@swiftycode.com . We can also chat about One Piece \u0026amp; Macbeth beside Swift -kidding- on Twitter at @swiftycode_com .\n ","permalink":"https://swiftycode.com/blog/posts/part-iii-filter/","summary":"Let\u0026rsquo;s learn what is .filter in Swift\u0026rsquo;s collections and much more about such Higher Order Functions \u0026hellip;","title":"Part (III) : What is .filter in Swift ?"},{"content":"It\u0026rsquo;s simple ! Let\u0026rsquo;s start with :\n.map : The whole idea is about mapping collection elements , do something on them and then return the same-sized array of them !\nSo, here we are creating a new array from the other array . It is done with an O(n) complexity since it iterates through the whole array .\n What is O(n)? it\u0026rsquo;s just a simple measure helping us represent the algorithms complexity. Soon I\u0026rsquo;ll publish an article on What is O(n) ? Swifty way and examples to help you understand it better .\n Well let\u0026rsquo;s see an example on .map in Arrays to help you understand it better :)\nimport Foundation var array = [2, 3, 4, 5] // 1. Just pass a closure as parameter in .map function and that's that ! let newArray_ModernStyle = array.map { (element) -\u0026gt; Int in element * element } print(newArray_ModernStyle) // Result -\u0026gt; [4, 9, 16, 25] //2. It's what swift offers to help us live better :) $0 acts as (element) in _ModernStyle's map closure. let newArray_SwiftyWay = array.map { $0 * $0 } print(newArray_SwiftyWay) // Result -\u0026gt; [4, 9, 16, 25] //3. What if there weren't any .map in Swift? Oh... S*#! var newArray_OldFashioned: [Int] = [] for element in array { newArray_OldFashioned.append(element * element) } print(newArray_OldFashioned) // Result? The same as above! What did you expect?!  O\u0026hellip;K, but what about return? To make it easier than what you can find at swift.org:\n While having only one line of code inside the closure , our smart complier understands that it\u0026rsquo;s what we wanted to return! element * element is the same as return element * element for the compiler in this case .\n Gotcha! Wondering WTH is $0 ?! As it is explained at swift.org:\n \u0026hellip; $0 and $1 refer to the closure’s first and second arguments\u0026hellip; . You\u0026rsquo;ll see $1 in future examples but for now , it\u0026rsquo;s enough to know that $0 simply is the first (in our case the only) argument that .map closure offers ;)\n Let\u0026rsquo;s meet .map\u0026rsquo;s brothers - or maybe sisters :) .compactMap and .flatMap !\n.compactMap : Well , as I\u0026rsquo;ve already mentioned in the first part of this series , Swift\u0026rsquo;s collection types are implemented as generic types . The same thing goes for also the collections' in-built functions :) It means that there isn\u0026rsquo;t any restrictions on using .map with Array or Array just like Array !\nThe interesting thing here is that they also work with Optional Types ! What would happen if the .map(ped) array result in some nil values ? Here\u0026rsquo;s where our new Savior shows up :) Ladies \u0026amp; Gentlemen let me introduce you the .compactMap !\nimport Foundation var array = [\u0026quot;2\u0026quot;, \u0026quot;3\u0026quot;, \u0026quot;Four\u0026quot;, \u0026quot;Roronoa Zoro\u0026quot;] let newArray_ModernStyle = array.map { (element) -\u0026gt; Int? in Int(element) } print(newArray_ModernStyle)  Can you guess the result? It\u0026rsquo;s an Optional array of Ints :) Why Optional? because the Downcast of String to Int might fail - Just like what\u0026rsquo;s happening here . So to make the above example more readable :\n... let newArray_ModernStyle: [Int?] = array.map { (element) -\u0026gt; Int? in //element is a String Int(element) } print(newArray_ModernStyle) // Result -\u0026gt; [Optional(2), Optional(3), nil, nil]  Wait , wait \u0026hellip; What just happened ?! Do you remember what I said about .map ? \u0026hellip; do something on each element and then return the same-sized array of them \u0026hellip; - Yep! .map should return the same-sized array as the inputed array . In our case some of the Downcasts fail and as we expecting the same-sized array from .map to be _throw_n , it fills the array with nil as for failed Downcasts .\nI guess that you\u0026rsquo;ve already guessed \u0026hellip; Here is where .compactMap enters!\nTo make what developer.apple.com says about it :\n .compactMap is almost the same as .map with one difference ; .compactMap discards all of nil results so the newArray contains only valid transformed elements. And here we don\u0026rsquo;t expect the same-sized array to be returned . .compactMap returns an array containing the non-nil results of calling the given transformation with each element of this sequence !\n import Foundation var array: [String] = [\u0026quot;2\u0026quot;, \u0026quot;3\u0026quot;, \u0026quot;Four\u0026quot;, \u0026quot;Roronoa Zoro\u0026quot;] let newArray_ModernStyle = array.compactMap { (element) -\u0026gt; Int? in Int(element) } print(newArray_ModernStyle) // Result -\u0026gt; [2, 3] let newArray_SwiftyWay = array.compactMap { Int($0) } print(newArray_SwiftyWay) // Result -\u0026gt; [2, 3]   What exactly is Optional behind the scenes ? It\u0026rsquo;s built using Enum with two cases of some value and .none . I\u0026rsquo;d soon publish an article on What is Optional in Swift ? Behind the scenes to cover the whole thing !\n Here is the magic of .compactMap ! As it returns an array containing the non-nil results\u0026hellip; it discards the nil and (if needed) unnecessary results just like Optional parts of Int? . To be more clear , it converts the Optional value since it knows that the result can\u0026rsquo;t be nil ,so using Optionals is absolutely useless . But if you declare newArray as type [Int?] in the above example it would produce an array of Optional Ints while holding nils -just like big bro, .map .\n It\u0026rsquo;s good to know that the complexity of ,compactMap as developer.apple.com says is O(m +n) . Thats because it iterates through the whole array of n times and produces an array of m items .\n By the way, who was that Roronoa Zoro guy in our array ? He is a legend, the greatest swordsman in the whole New World, Vice Captain of Straw Hat Pirates =))))) I deeply suggest you to go and watch One Piece .In the Anime, there is only one thing wrong about Roronoa , and that\u0026rsquo;s he always loses his way and his sense of direction is absolutely awful . This time as he got lost it seems that he were here with us ;)\nLet\u0026rsquo;s learn about the last .map\u0026rsquo;s brother -or maybe sister- and wrap this up -so we can go and enjoy the Holy One Piece :)\n.flatMap : It\u0026rsquo;s simple . As of introducing .compactMap beside Swift 4.1 it got even simpler than before .\nNowadays the only thing .flatMap does is to :\n \u0026ldquo;Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.\u0026rdquo;\n-developer.apple.com\n To make it readable by humans ,\n \u0026ldquo;in Swift 4.1+ .flatMap is used only to help you flattening a nested collection into a single array.\u0026rdquo;\n-Alireza\n Well, a nested collection is like an array having another array as its elements . Like an array of arrays !\nimport Foundation var array: Array\u0026lt;[Int]\u0026gt; = [[1], [2, 3, 4, 5], [6, 7]] let newArray_ModernStyle = array.flatMap { (element) -\u0026gt; [Int] in element } print(newArray_ModernStyle) let newArray_SwiftyWay: [Int] = array.flatMap { $0 } print(newArray_SwiftyWay)  Wondering about the result? It\u0026rsquo;d be -\u0026gt; [1, 2, 3, 4, 5, 6, 7] . The whole array in flattened by .flatMap to make our newArray .\n There are two things here that could be nice to point out . The .flatMap\u0026rsquo;s closure always returns Sequence and it\u0026rsquo;s also good to know that Arrays , Sets , Dictionaries and lots of collection types conform to Sequence Protocol .\n As developer.apple.com mentions , Sequence is a type that provides sequential, iterated access to its elements. Simply it\u0026rsquo;s a list of values that you can step through one at a time . Consider iterating over a Sequence has complexity of O(n) .\nBefore putting an end to this topic , just like .compactMap , .flatMap has complexity of O(m + n) ! The reason is simple , isn\u0026rsquo;t it? :)\nNext: Part (III) : What is .filter in Swift ?\n Thanks a lot for coming this far and reading the article :) As you may know it\u0026rsquo;s a series about Higher Order Functions of Swift\u0026rsquo;s Collection , so make sure to read next articles as well as previous one -if you hadn\u0026rsquo;t already- to completely master this subject . Stay Safe , Code Well \u0026amp; Watch One Piece =)\n If you have any questions, suggestions or etc. feel free to contact me at alireza@swiftycode.com . We can also chat about One Piece beside Swift -kidding- on Twitter at @swiftycode_com .\n ","permalink":"https://swiftycode.com/blog/posts/part-ii-map-compactmap-flatmap/","summary":"Let\u0026rsquo;s dig in our very first and also one of the most useful Higher Order functions in Swift\u0026rsquo;s collections !","title":"Part (II) : What are .map , .compactMap and .flatMap in Swift"},{"content":"Ok Ok, first of all , What are collections in Swift? It\u0026rsquo;s simple!\nAs mentioned in swift.org :\n Swift provides three primary collection types (arrays, sets, and dictionaries) for storing collections of values.\n Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.   \u0026hellip; note that these collection types are implemented as generic types.\nAssuming that you\u0026rsquo;re familiar with at least one of these types, let\u0026rsquo;s get familiar with the hero, Higher Order functions !\nHigher Order functions They\u0026rsquo;re really simple ! Higher order functions are ones that deal with other functions, either as a parameter or as a return type .\nAs far as we need them for this series is that there are some higher order functions built by swift for collection types such as .map, .compactMap, .flatMap, .split , .filter, .reduce, .forEach and .sort.\nWe\u0026rsquo;d also try to see what our world would be without these lovely functions by example while learning how to make our life easier with them .\nBelieve me, they\u0026rsquo;d make your coding life much easier - swiftier :)\nLearn about .map, .compactMap and .flatMap in the next exciting episode =)\nNext: Part (II) : What are .map , .compactMap and .flatMap in Swift?\n","permalink":"https://swiftycode.com/blog/posts/part-i-higher-order-functions-in-swift-collections/","summary":"Ok Ok, first of all , What are collections in Swift? It\u0026rsquo;s simple!\nAs mentioned in swift.org :\n Swift provides three primary collection types (arrays, sets, and dictionaries) for storing collections of values.\n Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.   \u0026hellip; note that these collection types are implemented as generic types.\nAssuming that you\u0026rsquo;re familiar with at least one of these types, let\u0026rsquo;s get familiar with the hero, Higher Order functions !","title":"Part (I) : What are Higher Order functions in Swift's collections ?"},{"content":"XiComic — Support Last updated: 25 July 2025\nThank you for using XiComic – Comic \u0026amp; Manga Reader.\nWe’re here to help with questions, feedback, or bug reports.\n 📧 Contact Us  Email: self@alireza.codes\nWe aim to reply within 24 hours on weekdays.   ❓ Frequently Asked Questions    Question Answer     How do I import my comics? In Library ▶ ＋ Add Comics choose Files, AirDrop, Share Sheet or Drag \u0026amp; Drop CBZ, CBR, ZIP, RAR, or a whole folder.   Does XiComic collect any data? No. All comics stay on your device unless you manually move them to iCloud Drive. See our full policy below.   The app crashed—what should I do? Email us with your device model, iOS/iPadOS version and steps to reproduce, Manyyy thanks in advance.   Can I request a feature? Absolutely! Send your idea to our support email self@alireza.codes; we track every suggestion.     🔐 Privacy \u0026amp; Legal XiComic is designed to be privacy-first.\nPlease review our Privacy Policy to learn how we handle (or deliberately avoid) data collection.\n © 2025 XiComic. All trademarks are property of their respective owners.\n","permalink":"https://swiftycode.com/blog/support/","summary":"XiComic — Support Last updated: 25 July 2025\nThank you for using XiComic – Comic \u0026amp; Manga Reader.\nWe’re here to help with questions, feedback, or bug reports.\n 📧 Contact Us  Email: self@alireza.codes\nWe aim to reply within 24 hours on weekdays.   ❓ Frequently Asked Questions    Question Answer     How do I import my comics? In Library ▶ ＋ Add Comics choose Files, AirDrop, Share Sheet or Drag \u0026amp; Drop CBZ, CBR, ZIP, RAR, or a whole folder.","title":""}]