Struct Definition in Swift

Level 3158 keystrokes

Defines a Point struct with two stored properties and a method that returns the distance from the origin. For x = 3 and y = 4 it prints 5.0.

Swift code

// A struct is a value type: copies are independent
1struct Point {
// Two stored properties for the coordinates
2 var x: Double
3 var y: Double
4
// Method that returns the distance from the origin (0, 0)
5 func distance() -> Double {
// Pythagorean theorem: square root of x² + y²
6 return (x * x + y * y).squareRoot()
7 }
8}
9
// The memberwise initializer is generated automatically; 3 and 4 become Double
10let p = Point(x: 3, y: 4)
// sqrt(9 + 16) = 5, printed as 5.0
11print(p.distance())

Output

5.0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • (× 6
  • )× 6
  • :× 4
  • .× 2
  • {× 2
  • }× 2
  • *× 2
  • -× 1
  • ,× 1
  • +× 1

More Swift examples at level 3

← Swift typing practice