DEV Community

Naveen Ragul B
Naveen Ragul B

Posted on • Edited on

Swift - Structure and Class

  • Both Structure and Class can define property, method, subscript, initializers, can be extended and conform to a protocol.

  • Features only class have but structure don't have - Inheritance, TypeCasting, De-initializer, Reference Counting (allows more than one reference to a class instance)

example :

struct Resolution {
    var width = 0
    var height = 0
}
class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}
Enter fullscreen mode Exit fullscreen mode
let someResolution = Resolution()
let someVideoMode = VideoMode()
Enter fullscreen mode Exit fullscreen mode
  • Memberwise Initializers for Structure Types - All structures have an automatically generated memberwise initializer, which you can use to initialize the member properties of new structure instances.

  • Structures and Enumerations Are Value Types
    A value type is a type whose value is copied when it’s assigned to a variable or constant, or when it’s passed to a function.

Integers, floating-point numbers, Booleans, strings, arrays and dictionaries—are value types in swift, and are implemented as structures behind the scenes.

  • Classes Are Reference Types. Reference types are not copied when they’re assigned to a variable or constant, or when they’re passed to a function.

  • classes are reference types, it’s possible for multiple constants and variables to refer to the same single instance of a class. Identity operator is used to check whether two constants or variables refer to the same single instance.

  1. Identical to (===)
  2. Not identical to (!==)

Top comments (0)