Tuesday 27 December 2016

Enums - Structs - Classes in Swift

Enums:
  • An enumeration defines a common type for a group of related values.
  • Enums are value types that have a set of cases, where each case can have different associated values. 
  • Each value of an enum type represents a single case as defined by the enum. 
  • They can’t have any stored properties.(let, var)

Syntax:
enum SomeEnumeration {
  // enumeration definition goes here
}


Structs:


Common features for Classes and Structs:

  • Define properties to store values 
  • Define methods to provide functionality 
  • Define subscripts to provide access to their values using subscript syntax 
  • Define initializers to set up their initial state 
  • Be extended to expand their functionality beyond a default implementation 
  • Conform to protocols to provide standard functionality of a certain kind
Extra benefits of classes:
  • Inheritance enables one class to inherit the characteristics of another. 
  • Type casting enables you to check and interpret the type of a class instance at runtime. 
  • Deinitializers enable an instance of a class to free up any resources it has assigned. 
  • Reference counting allows more than one reference to a class instance.
Syntax:
struct SomeStructure { 
   // structure definition goes here
}


Classes:

Unlike value types, reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function. Rather than a copy, a reference to the same existing instance is used instead.
Syntax:
class SomeClass {  
  // class definition goes here
}