Skip to content

Exercises 7 ​

The exercises in this series use the Vector and Circle types from Structures:

import Foundation

struct Vector {

  var x: Double
  var y: Double

  var length: Double {
    sqrt(x * x + y * y)

struct Circle {

  var center: Vector
  var radius: Double

Exercise 7.1 ​

Add mutating add(_:) and subtract(_:) methods to Vector. These methods add or subtract a vector to or from the current one.

Exercise 7.2 ​

Add non-mutating adding(_:) and subtracting(_:) methods to Vector. These methods return a new vector instead of modifying the current one.

Exercise 7.3 ​

Add a distance(to:) method to Vector that calculates the distance between a given vector and the current one.

Exercise 7.4 ​

Declare a type Rectangle that has two stored properties of type Vector. These properties represent two opposing corners of the rectangle.

Exercise 7.5 ​

Add two initializers to Rectangle: one that takes a pair of x and y coordinates for one of the corners, a width, and a height; and one that takes two opposing corners.

The second initializer should verify that the given points are not on the same horizontal or vertical line. If that’s the case, the initializer should fail and return nil.

Exercise 7.6 ​

Add computed properties width, height, and area to Rectangle.

Exercise 7.7 ​

Add read-write computed properties diameter, circumference, and area to Circle.

Exercise 7.8 ​

Add a static property unit to Circle. This property holds a circle with radius 1, centered at (0, 0).