Swift Object Initialization

Korey Hinton -> Blog -> iOS -> Swift Object Initialization

How to initialize swift objects

The method signature for swift initializers differs from regular functions in that you don't put func at the beginning of the initializer. Inside of a class (or enum) you simply put init(). The syntax is kind of different than objective-c for named parameters since for it to be a recognized initializer the named parameters go inside the parentheses.

class MyObject {

    var frame : CGRect

    init() {
        self.frame = CGRectZero
    }

    init(frame: CGRect) {
        // same as Objective-C's -(void)initWithFrame:(CGRect)frame;
        self.frame = frame // frame is the variable name
    }

    func myFunction() {
       println("myFunction()")
    }

  /* This is not valid and will not compile:
  initWithFrame(frame: CGRect) { }
  Initializers must start with init(..
  */

}

Subclass Initializer

If your object is subclassing (inheriting) from another object then you call one of the super class's initializers in your init method. Before calling the super class's initializer you must set all properties that do not have the question mark signifying optional chaining (meaning that the property might be nil).

class Person {

    var age : Int
    var name : String

    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }

}

class Student : Person {

    var car : String? // optional
    var school : String // required to be set before calling super.init

    init(age: Int, name: String, school: String) {
        self.school = school
        // no compiler warning for not setting car
        super.init(age: age, name: name)
    }

}

Date: 2014-07-08T13:04+0000

Author: Korey Hinton

Org version 7.9.3f with Emacs version 24

Validate XHTML 1.0