Game Development Reference
In-Depth Information
Structures
Swift structures are similar to classes. Like classes, they can have initializers, properties,
and methods, and you must use labeled parameters when you pass values to their methods
and initializers. The biggest difference is that when you pass a structure to another method
or function, it is copied as opposed to being passed by reference like classes.
To implement a structure, you use the keyword struct followed by a set of braces and
then its implementation.
struct LatLong {
var lat : String
var long : String
func stringValue() ->String {
return "My location is \(lat) : \(long)"
}
}
In this structure you are defining a simple representation for a location based on a latitude
and a longitude. It has two properties, lat and long , and one method,
stringValue() , that returns a String representing the LatLong . To use this struc-
ture, you can call it using the following two lines of code:
let location = LatLong(lat: "39.7392 N", long: "104.9847 W")
println(location.stringValue())
As you can see, it looks like how you use a class. You might have noticed there is another
difference between classes and structures. All structures have an automatically generated
memberwise initializer, but classes do not. You can pass values to the initializer of a struc-
ture without creating the initializer.
Enumerations
To implement a Swift enumeration, you use the keyword enum followed by its type and a
set of braces with a case or collection of case statements defining the members of the
enum . Take a look at this enum defining an enumeration containing each day of the
week:
Search WWH ::




Custom Search