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. ...

Get Learning Xcode 8 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.