Structures and classes
In Swift, structures and classes are used to define custom data types. They have similar features but are distinct. (We already know that Bool
, Double
, Float
, Int
, and String
are basic data types.) Structure and classes define a set of different fields (stored properties) and functions (methods) that are applicable to the object and all related types. The good side of these custom types is that we can combine them when we are implementing our software ideas.
Note
Basic data types are implemented as structures.
Here is how we define a structure:
struct Car {
var name:String = "missing name"
var speed = 0
var maxSpeed = 200
}
Here is how we define a class:
class Ship {
var speed = 0
var isFlying = false
var description:String {
get {
return "The ship speed is \(self.speed) and it
can\(self.isFlying ? "" : "not") fly."
}
}
}
The first difference is that we are using different keywords, struct
and class
. But the final result is that...