Class Definition in Swift

Level 4232 keystrokes

Defines a Person class with two properties, an initializer and a method that builds a description string. It prints Alice, age 30.

Swift code

// A class is a reference type: variables share the same instance
1class Person {
// Properties without default values must be set in init
2 var name: String
3 var age: Int
4
// Classes get no memberwise initializer, so init is written by hand
5 init(name: String, age: Int) {
// self.name is the property, name is the parameter
6 self.name = name
7 self.age = age
8 }
9
// Returns a description built with string interpolation
10 func describe() -> String {
11 return "\(name), age \(age)"
12 }
13}
14
// Calls init with labeled arguments
15let p = Person(name: "Alice", age: 30)
// Prints Alice, age 30
16print(p.describe())

Output

Alice, age 30
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.

  • (× 7
  • )× 7
  • :× 6
  • "× 4
  • ,× 3
  • .× 3
  • {× 3
  • }× 3
  • =× 3
  • \× 2

More Swift examples at level 4

← Swift typing practice