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 independent1struct Point { // Two stored properties for the coordinates2 var x: Double3 var y: Double4 // 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 Double10let p = Point(x: 3, y: 4)// sqrt(9 + 16) = 5, printed as 5.011print(p.distance())Output
5.0
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