Skip to content

Exercises 7 ​

Create a package named exercises-7, 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.

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

swift
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:

  • add(_:) adds a given vector to self.
  • subtract(_:) subtracts a given vector from self.

Note

Here, we use self to refer to the instance that performs the method, not to the keyword. You can solve this exercise with or without using the keyword self.

Exercise 7.2 ​

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

Exercise 7.3 ​

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

Exercise 7.4 ​

Create two vectors v1 and v2. Next, create a new vector v3 by adding v1 and v2. Finally, print the length of v3.

Exercise 7.5 ​

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

Exercise 7.6 ​

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.7 ​

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

Exercise 7.8 ​

Create a rectangle that has v1 and v2 as corners, then print the width, height, and area of this rectangle.

Exercise 7.9 ​

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

Exercise 7.10 ​

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

Exercise 7.11 ​

Create two circles of equal size centered at v1 and v2. Set their radii so that the circles are touching, but not overlapping.