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 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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.