Creating classes, structs, and enums
So now we've covered the building blocks of programming in Swift. Our next step is to understand how to put these pieces together in an object-oriented programming environment. To do that, we're going to need to learn about classes, structs, and enumerations in Swift.
Classes
Classes in Swift are composed of properties and methods (functions). Let's jump right into an example:
class MyClass { var myInt: Int var myFloat: Float private var myOptString: String? init () { myInt = 0 myFloat = 0 } func generateString() -> String { myOptString = "\(myInt) \(myFloat)" return myOptString! } }
On the first line, you see the beginning of the class declaration, beginning with the class
keyword, followed by the class name. Class names in Swift should always be capitalized. The rest of the class
declaration is inside a set of curly braces.
At the top of the class...