The Swift language offers both structs and classes. Both structs and classes can have properties and methods, including constructors. The most important difference between structs and classes is that structs are value types, while objects are reference types. When you pass a struct to a function as a parameter, you pass a copy of the value of the struct. When you pass an object to a function it always gets passed by reference.
struct Rectangle {
var width : Double
var height : Double
}
Defining a struct or a class automatically defines a constructor for that type:
let r = Rectangle(width:25.0,height:15.0)
Like Kotlin, Swift also allows you to set up computed properties:
struct Rectangle {
var width : Double
var height : Double
var area : Double {
get {
return width*height
}
}
}
let r = Rectangle(width:25.0,height:15.0)
println("The area of r is \(r.area).")
Computed properties that only have getters can also be written in a more compact notation:
struct Rectangle {
var width : Double
var height : Double
var area : Double {
return width*height
}
}