Kinga
Kinga

Reputation: 11

Initializers may only be declared within a type / coder

I use this tutorial in order to create a simple Shopping List app. I have a problem with those lines of code:

override func viewDidLoad() {
    super.viewDidLoad()

    required init?(coder aDecoder: NSCoder) {   // error appears here
        self.init(coder: aDecoder);

        loadItems()
  }
}

There is an error: Initializers may only be declared within a type. Why it is not correct? What should I change here?

Upvotes: 0

Views: 2641

Answers (1)

nathangitter
nathangitter

Reputation: 9777

Initializers must be placed at the type level, not inside any other functions.

class Item: NSObject, NSCoding {

    required init?(coder aDecoder: NSCoder) {
        self.init(coder: aDecoder)
        loadItems()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // this code runs when the view loads
    }

    func loadItems() {
        // item loading code here
    }

}

Upvotes: 1

Related Questions