Skip to content

Exercises 5 ​

These exercises focus on using arrays and dictionaries.

As with the previous exercises, whenever you’re asked to declare a function, it’s up to you to choose appropriate parameters, argument labels, and return values. Also, include at least one function call with every function you declare, to show that you know how to call the function.

Exercise 5.1 ​

Declare a function to calculate the sum of an array of numbers.

Exercise 5.2 ​

Declare a function that takes an array of numbers and returns a new array where the order of the elements is reversed.

This is exactly what the reversed method of type Array does. Your solution shouldn’t rely on this method; the exercise is to implement it yourself.

Exercise 5.3 ​

Declare a function that takes an array of numbers and returns a new array where the elements are sorted from small to large.

This is exactly what the sorted method of type Array does. Your solution shouldn’t rely on this method; the exercise is to implement it yourself.

Exercise 5.4 ​

Declare a function characters(in:) that checks which characters occur in a string and returns the number of times each of these characters occur.

Like arrays and dictionaries, strings are collections. This means you can use a for-in loop to iterate over the characters in a string:

swift
var string = "some string"
for character in string {
  // ...
}

You’ll need this to solve the exercise.

Exercise 5.5 ​

Declare a function words(in:) that checks which words occur in a string and returns the number of times each of these words occur.

Exercise 5.6 ​

Declare a function stats(for:) that returns the number of lines, words, and characters in a string.