1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import Foundation
/// A point in 2D space.
struct Point {
var x: Double
var y: Double
func distanceTo(_ other: Point) -> Double {
let dx = x - other.x
let dy = y - other.y
return (dx * dx + dy * dy).squareRoot()
}
}
/// Protocol for shapes that can compute area.
protocol Shape {
func area() -> Double
func perimeter() -> Double
}
/// A circle shape.
class Circle: Shape {
let center: Point
let radius: Double
init(center: Point, radius: Double) {
self.center = center
self.radius = radius
}
func area() -> Double {
return Double.pi * radius * radius
}
func perimeter() -> Double {
return 2 * Double.pi * radius
}
}
enum Direction {
case north, south, east, west
func opposite() -> Direction {
switch self {
case .north: return .south
case .south: return .north
case .east: return .west
case .west: return .east
}
}
}
func greet(name: String) -> String {
return "Hello, \(name)!"
}