From Objective-C Classes to Swift Classes

Korey Hinton -> Blog -> iOS -> From Objective-C Classes to Swift Classes

Swift Class Equivalent to Objective-C

../../media/swift-hero.png

One of the first essentials to learn when going from Objective-C to Swift is how to create a class. In Swift there are no header files, so the entirety of your class, both its public and private API are in 1 file instead of 2. In a Swift file you do not need to worry about importing your other Swift files. So any Swift class you create will be available in any of your other swift files.

Simple class definition

class Game {

}

Now to construct an object of your class Game:

var game = Game()

More complete class definition

You many want to have an init method along with properties like you would in Objective-C. This is easy:

class Game {
    var lives : Int
    var score : Int
    init(lives: Int) {
        self.lives = lives
        self.score = 0
    }
}

Now to construct and manipulate an object of this class:

var game = Game(10)
game.score += 10
game.lives--

Inheritance

You may want to have your classes inherit from each other. Or if you want your class to receive callbacks from Objective-C classes (ie: NSTimer) you will need to inherit from NSObject or some other subclass of NSObject. You will need to call the parent constructor after setting all your properties.

class Game: NSObject {
    var lives : Int
    var score : Int
    init(lives: Int) {
        self.lives = lives
        self.score = 0
        super.init()
    }
}

If you want to set the properties of the parent class, you will do that after its initialization. I show that in an example below where we subclass Game:

class LevelGame: Game {

    var level : Int

    init(level: Int) {
        self.level = level
        super.init(10) // 10 lives
        score = 1 // parent's score
    }
}

Conforming to Protocols

Conforming to protocols has the same syntax as inheritance but any inherited superclasses need to be listed before the protocols a class is conforming to. Here's an example below where we assume another class is loads the game and LevelGame will be its delegate, so we will get the callback when it is done and we will conform to its protocol GameLoaderDelegate.

protocol GameLoaderDelegate {
    func gameDidLoad()
}
class LevelGame: Game, GameLoaderDelegate {

    var level : Int
    var loader : GameLoader
    init(level: Int) {
        self.level = level
        self.loader = GameLoader()
        super.init(10) // 10 lives
        score = 1 // parent's score
        loader.load()
    }
    func gameDidLoad() {
        // do something, start the game, etc.
    }
}

Date: 2014-07-15T14:48+0000

Author: Korey Hinton

Org version 7.9.3f with Emacs version 24

Validate XHTML 1.0