The Anatomy of a Swift Class

By Jesse Feiler

Part of Swift For Dummies Cheat Sheet

Classes are the heart of any object-oriented programming language. Unlike classes in Objective-C and some other languages, Swift’s classes need no header declaration. Instead, you get the entire class (or structure or enumeration) definition in a format like this:

class MyClass {
 var storedNumber: Int = 0
 init (myNumber storedNumber: Int) {
 self.storedNumber = storedNumber
 }
 func simpleDescription() -> String {
  return String(self.storedNumber)
 }
}
var test = MyClass(myNumber: 15)
println ("myNumber is " + test.simpleDescription());

The code in this example defines a class. Note the following characteristics:

  • It declares a stored property. It is an Int set initially to 0.

  • It creates an initializer that takes an Int as a parameter. The external name is myNumber and the internal name is storedNumber. The initializer sets the class instance value self.storedNumber using the storedNumber parameter (with the external name myNumber).

  • It declares a function called simpleDescription that returns a String representation of the stored number.