With extensions in Swift one can:

  • add computed instance properties and computed type properties
  • define instance methods and type methods
  • provide new initializers
  • define subscripts
  • define and use new nested types
  • make an existing type conform to a protocol

To start with, let's create and define a base class, struct, and enum—which we are going to extend later.

Class

This class has two properties and an initializer.

/*                  
  ┌────────────────┐
  │     Cattle     │
  ├────────────────┤
  │gender: Gender  │
  │age: Int        │
  └────────────────┘
*/                                 

class Cattle {
  var gender: Gender
  var age: Int
  
  init(gender: Gender, age: Int) {
    self.gender = gender
    self.age = age
  }
}
   
let cow = Cow(gender: .female, age: 20)

Structure

The same as above but defined as a structure.

struct Cattle {
  var gender: Gender
  var age: Int
}
   
var cow = Cattle(gender: .female, age: 20)

Enumeration

This enumeration has a set of enumeration cases only

/*
 ┌─────«enum»─────┐
 │     Gender     │
 ├────────────────┤
 │male            │
 │female          │
 └────────────────┘
 */

enum Gender {
  case male, female
}

Extending by adding computed instance and type properties

Extending a class

extension Cattle {
  
  var sound: String {
    
    get {
      if age < 12 { return "*bawling*" }
      else if gender == .male   { return "*bellow*" }
      else if gender == .female { return "moo" }
    }
    
    set {
      if newValue == "bawling" { age = 10 }
      else if newValue == "bellow" { gender = .male }
      else if newValue == "moo" { gender = .female }
    }
  }
  
}