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 instance1class Person { // Properties without default values must be set in init2 var name: String3 var age: Int4 // Classes get no memberwise initializer, so init is written by hand5 init(name: String, age: Int) { // self.name is the property, name is the parameter6 self.name = name7 self.age = age8 }9 // Returns a description built with string interpolation10 func describe() -> String {11 return "\(name), age \(age)"12 }13}14 // Calls init with labeled arguments15let p = Person(name: "Alice", age: 30)// Prints Alice, age 3016print(p.describe())Output
Alice, age 30
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