Skip to content

Exercises 4 ​

Create a package named exercises-4, delete its existing source file, and create a main.swift file. Put your solutions in this file, and when you’re done, compare your work with the solutions bundle.

These exercises focus on using tuples and optionals. 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 for your functions, and to try out each function by calling it with various arguments.

Exercise 4.1 ​

Note

This exercise builds on Exercise 1.7.

Declare a function to calculate the integer quotient and floating-point remainder of a division of two floating-point numbers.

Exercise 4.2 ​

Note

This exercise builds on Exercise 1.9.

Declare Point as a type alias for a tuple that represents a two-dimensional point.

Next, declare a function to calculate the distance between two points.

Exercise 4.3 ​

Note

This exercise builds on Exercise 2.2.

Declare a function that, given the coefficients a, b, and c of the quadratic equation ax2+bx+c=0, calculates the solutions x1 and x2 for this equation.

Exercise 4.4 ​

Note

This exercise builds on Exercise 2.1.

Declare Position as a type alias for a pair of coordinates on a chessboard.

Next, declare a function that, given a position on the chessboard, calculates the next position. Unlike Exercise 2.1, this function should not wrap from (7, 7) to (0, 0). Instead, consider (7, 7) as the last position.

Exercise 4.5 ​

A caller of the previous function may decide to wrap from (7, 7) to (0, 0) anyway. Show how you can achieve this without modifying the function.