Swift Introduction | Structures, Enumerations, and Tuples | Structures
Swift has values with complex behavior in addition to classes and arrays. We begin with structures.
A structure has properties that store values and methods that implement processing. To use a structure, define it and create instances from that definition. This may sound similar to a class.
The basic construction and the handling of properties and methods are almost identical to classes, but there are important differences.
Defining a Structure with struct
Classes are defined with class Name, while structures use struct Name. Properties and methods are written in the same way.
struct Name {
... write properties and methods ...
}
No Inheritance
Structures do not have the same object-oriented inheritance mechanism as classes. They group values and processing together, but cannot be inherited to create new structures.
No Initializer Required
For a structure with properties, Swift automatically creates an initializer that receives values for those properties.
Values Are Copied
This difference is important. A class instance is referenced through a variable. Assigning that variable to another variable copies the reference, so both variables refer to the same instance.
Structures do not use this reference behavior. Assigning a structure instance to another variable copies the structure itself, so the two variables hold different instances.
struct MyData {
var age:Int
var name:String
func getData() ->String {
return "[\(name)(\(age))]"
}
}
var data = MyData(age: 99, name: "Taro")
var data2 = data
data2.name = "Hanako"
data2.age = 24
println(data.getData())
println(data2.getData())
The code creates a MyData structure and an instance. Swift automatically provides the initializer used by MyData(age: 99, name: "Taro").
Although data is assigned directly to data2, changing the properties and printing the results shows that each variable holds a separate instance.