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:
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 toself
.subtract(_:)
subtracts a given vector fromself
.
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.