Search code examples
iosswiftswift-playground

Cannot assign self as delegate in property initializer


I am getting a strange error message when I try to access self when initializing a property on my class. It seems like my class has a weird type.

This is the error:

Cannot assign a value of type 'ViewController -> () ViewController' to a value of type 'ModelControllerDelegate?'

This is the code, simple example in a playground:

import Foundation
import UIKit

protocol ModelControllerDelegate
    {
    func modelControllerDidFinishTask()
    }

class ModelController
    {
    var delegate : ModelControllerDelegate?
    }

class ViewController : UIViewController, ModelControllerDelegate
    {
    var modelController : ModelController =
        {
        let controller = ModelController()
        controller.delegate = self
        return controller
        }()

    func modelControllerDidFinishTask()
        {

        }
    }

Solution

  • You are trying to use self when not fully initialised. Might work if you use a lazy initialisation:

    lazy var modelController : ModelController = { ...