Iterating Through Collection Types In Swift
Collection types in swift are the arrays, the dictionaries and the sets. Iterating through them is really easy using the for-in loop. The purpose of this article is to gather all the related information in one point, neat?
Lets start with the arrays. We have an array of Strings and we want to print the contents, each name in a new line.
[sourcecode language=“objc”] let classMates = [“Marinos”, “Stuart”, “Thomas”, “Kirsty”, “Carlos”] for mate in classMates { print(“\mate)”) } [/sourcecode] The output will be: MarinosStuartThomasKirstyCarlosA for-in loop with a print using string interpolation will do the job.
What if we want to include an index in front. Don’t think of something complex, the solution is enumerate(). This function return a tuple containing the index (starts from zero) and the array item. So it will looks like:
[sourcecode language=“objc”] for (i, name) in classMates.enumerate() { print(“\i + 1). \name)”) } [/sourcecode] and the output will be: 1. Marinos2. Stuart3. Thomas4. Kirsty5. CarlosNext type is Dictionary. The story is almost the same. We will use for-in and tuples.
[sourcecode language=“objc”] let studentsAndMarks = [“Marinos”: 60, “Stuart”: 65, “Thomas”: 70, “Kirsty”: 65, “Carlos”:60] for (name, mark) in studentsAndMarks { print(“\name) - \mark)”) } [/sourcecode] with output: Kirsty - 65Thomas - 70Carlos - 60Stuart - 65Marinos - 60Do you want an index in front? You know the tip.
[sourcecode language=“objc”] for (i, (name, mark)) in studentsAndMarks.enumerate() { print(“\i). \name) - \mark)”) } [/sourcecode] and the output will be: 0. Kirsty - 651. Thomas - 702. Carlos - 603. Stuart - 654. Marinos - 60Don’t forget that if you want to get the array of keys or values from the dictionary is dead easy. Use the following;
[sourcecode language=“objc”] let matesNames = Array(studentsAndMarks.keys) let matesGrades = Array(studentsAndMarks.values) [/sourcecode] Last type is the Set. The story is repeated. Use for-in and that’s all.
[sourcecode language=“objc”] var starWarsPlanets: Set = [“Naboo”, “Tatooine”, “Mustafar”, “Coruscant”] for planet in starWarsPlanets { print(“\planet)”) } [/sourcecode] and the output will be: NabooTatooineMustafarCoruscantYes, I know that you are a demanding reader. Although set is an unordered collection type you want to print the results in alphabetic order. Ok then you should use sort()
[sourcecode language=“objc”] for planet in starWarsPlanets.sort() { print(“\planet)”) } [/sourcecode] with output: CoruscantMustafarNabooTatooineLast but not least, if you want to download the playground file follow that (Attachment missing: (Attachment missing: iterationsThroughCollections101))