Struct Definition in Swift

Level 3109 keystrokes

Defines a struct with two properties, creates it with the automatically generated memberwise initializer, changes x and prints "Point: (15, 20)".

Swift code

// struct defines a value type
1struct Point {
// Stored properties declared with var can be changed later
2 var x: Int
3 var y: Int
4}
5
// Swift generates the memberwise initializer Point(x:y:) automatically
6var p = Point(x: 10, y: 20)
// Allowed because both p and x are var (with let p it would not compile)
7p.x = 15
// The outer ( ) in the string are printed as-is: Point: (15, 20)
8print("Point: (\(p.x), \(p.y))")

Output

Point: (15, 20)
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.

  • :× 5
  • (× 5
  • )× 5
  • .× 3
  • ,× 2
  • "× 2
  • \× 2
  • =× 2
  • {× 1
  • }× 1

More Swift examples at level 3

← Swift typing practice