Rodrigo
Rodrigo

Reputation: 12683

Can I have a subclass of my class as property in Swift?

In Swift 2.1 I need to initialize every properties before use the class method. But if I want to have a property that is a subclass of it, I will have an infinite loop. Is this possible?

class Myclass {
    let mySubClass:SubClass
    init() {
        mySubClass = SubClass()
        print("Init my class")
    }
}

class SubClass:Myclass {
    override init() {
        print("Init subclass")
    }
}

let myClass = Myclass()

Upvotes: 1

Views: 61

Answers (2)

vadian
vadian

Reputation: 285082

You could use a lazy stored property.

The instance of the subclass isn't initialized until it's used the first time.

class Myclass {
  lazy var mySubClass : SubClass = {
    return SubClass()
  }()

  init() {
    print("Init my class")
  }
}

class SubClass:Myclass {
  override init() {
    print("Init subclass")
  }
}

let myClass = Myclass()
myClass.mySubClass

Upvotes: 3

Phillip Mills
Phillip Mills

Reputation: 31016

I think you're better off to be explicit about the relationships. Something like:

class Myclass {
    var mySubClass:SubClass?
    init() {
        print("Init my class")
    }
}

class SubClass:Myclass {
    override init() {
        print("Init subclass")
    }
}

var myClass = Myclass()
let mySub = SubClass()
myClass.mySubClass = mySub

Upvotes: 1

Related Questions