Structures and classes are general purpose flexible constants that become the building blocks of our programming code.
Comparing Structures and classes
Structures and classes in Swift have many things in common. Both can:
- Define properties to store values
- Define methods to provide functionality
- Define initializers to set up their initial state
- Conform to protocols to provide standard functionality of a certain kind
Classes have additional capabilities that structures don’t have:
- 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.
Definition Syntax
struct SomeStructure {
// structure definition goes here
}
class SomeClass {
// class definition goes here
}
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
Struct and class instances
let someResolution = Resolution()
let someVideoMode = VideoMode()
Struct vs Class
struct are light weight and clean and better Performance
we cannot have inheritance in struct.
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:
Top comments (0)