Classes: Your own custom types

Syntax:

class YourClass : OptionalSuperClass {
  // the definition
}

Classes are the building blocks of your program. Each class can have properties and methods that provide the implementation details of how to work with these custom objects. They can also be declared to implement certain protocols that provide a standard level of functionality. While classes and structures are very similar, classes do possess some additional features not found in structures:

  1. Inheritance of characteristics from a superclass
  2. Automatic Reference Counting allows mulitple references to the same object
  3. Type casting provides for checking the type of an object at runtime
  4. Classes can clean up their resources with a deinitializer
  5. Classes are passed by reference rather than copying their values

class SampleClass {
  var name: String = ""
  var number: Double = 0
  var squareNumber: Double
  {
    get {
      return number * number
    }
    set {
      number = sqrt(newValue)
    }
  }

  func checkNumber() -> String {
    return "The number is \(number)"
  }
}


// Create an instance of the class and set the values
var coconut = SampleClass()
coconut.name = "Four"
coconut.number = 4
println("The square of \(coconut.name) is \(coconut.squareNumber)")
// prints The square of Four is 16.0

let myOutput = coconut.checkNumber()
// sets myOutput to "The number is 4.0"

// Create another instance of the class with the same values
var banana = SampleClass()
banana.name = "Four"
banana.number = 4
if coconut === banana { // evaluates to false
  println("How did that happen?")
}

The example above shows a simple class with two normal properties, one computed property, and one method. The computed property requires get and set methods to perform the computation. In the set method, the value passed in is automatically turned into a constant named "newValue". To create an instance of this class, just assign it to a variable Also, since the objects store references to an instance of the given type, an additional Identity Operator is available to check if two variables point to the same instance. Note that even though "coconut" and "banana" contain exactly the same values, they point to separate intances of the SampleClass, and thus the Identity comparison returns false.