Working with structs in swift?
Example:
struct Point {
var x: Int
var y: Int
}
var p = Point(x: 5, y: 10)
Structs are used to define custom data types. The example shows a basic structure for a 2D point.
Solution:
struct Point {
var x: Int
var y: Int
func distance(to point: Point) -> Double {
let dx = Double(x - point.x)
let dy = Double(y - point.y)
return sqrt(dx*dx + dy*dy)
}
}
var p1 = Point(x: 5, y: 10)
var p2 = Point(x: 15, y: 20)
print(p1.distance(to: p2))
The solution adds a method to the struct to calculate the distance between two points.