Swift - Custom Type Structures

Introduction

Swift structures are similar to classes:

  • they have properties and methods in them,
  • they have initializers
  • they generally behave in an object.

You can use generics, subscripts, initializers, protocol conformance, and extensions to structures.

There are two main things that differentiate them from classes:

  • Structures do not have inheritance.
  • When you pass a structure around in your code, the structure is always copied.

Structures are declared using the struct keyword as follows:

struct Point { 
    var x: Int 
    var y: Int 
} 

If you don't provide any initializers, structures get a compiler-provided one, called the memberwise initializer:

let p = Point(x: 2, y: 3) 

In Swift, structures are value types, which are always copied when passed around.

Most of the common types in Swift, including Int, String, Array, and Dictionary, are implemented as structures.

Reference

structures are value types and classes are reference types.

Demo

struct NumberStruct { 
   var number  : Int 
} 
class NumberClass { 
   var number  : Int 

   init(_ number: Int) { 
       self.number = number 
   } //from w w  w  .  j a v  a 2s.c o m
} 

//If we have two instances of both of them, initially they are both what we expect: 

var numberClass1 = NumberClass(3) 
var numberClass2 = numberClass1 
print(numberClass1.number) // 3 
print(numberClass2.number) // 3 

var numberStruct1 = NumberStruct(number: 3) 
var numberStruct2 = numberStruct1 
print(numberStruct1.number) // 3 
print(numberStruct2.number) // 3 

//However, when we change them we can see the difference between the struct and class forms: 

numberStruct2.number = 4 
print(numberStruct1.number) // 3 

numberClass2.number = 4 
print(numberClass1.number) // 4

Result

Related Topics

Exercise