Structures and Classes in swift !

Structures and classes in swift are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions.

Structures and Classes

  • properties to store values
  • methods to provide functionality
  • 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
#Syntax

struct SomeStructure {
    // structure definition goes here
}
class SomeClass {
    // class definition goes here
}

#Example

struct Resolution {
    var width = 0
    var height = 0
}
class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}

Structure and Class Instances

The syntax for creating instances is very similar for both structures and classes

let someResolution = Resolution()
let someVideoMode = VideoMode()

Accessing Properties

You can access the properties of an instance using dot syntax. In dot syntax, you write the property name immediately after the instance name, separated by a period (.), without any spaces

print("The width of someResolution is \(someResolution.width)")

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.

let vga = Resolution(width: 640, height: 480)

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.

enum CompassPoint {
    case first, second, third, fourth
    mutating func seeWest() 
    {
        self = .west
    }
}

var currentDirection = CompassPoint.west

Classes Are Reference Types

Unlike value types, reference types are not copied when they’re assigned to a variable or constant, or when they’re passed to a function.

let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0

Identity Operators

Because classes are reference types, it’s possible for multiple constants and variables to refer to the same single instance of a class behind the scenes.

Identical to (===)
Not identical to (!==)

if tenEighty === alsoTenEighty 
{
    print("equals")
}

Happy Coding 🙂


Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top