Michael Ninh
Michael Ninh

Reputation: 802

swift - Initializing another class inside a class?

Hello everybody I am a beginner in programing FYI! This is the problem that I have: I have two classes: Human and Pet. The Pet class has a method called eat that prints a simple "eat" line. The Human class has a method that calls the eat method from the Pet class. The way I am trying to implement this is by creating a Pet object inside the Human class so that a Human method can call the Pet methods.

Is this a right way to go about this? I'm also running into problems attempting to create the Pet inside Human...

This is what I have so far:

class Human{
var humanName: String
var Pet = Pets(petName: String, noise: String, canMakeNoise: Bool)

init(humanName: String, petName: String, noise: String, canMakeNoise: Bool){
    self.humanName = humanName

func feedPet(){
        //insert Feed function here
    }

class Pets{
var petName: String
var noise: String
var canMakeNoise: Bool

init(petName: String, noise:String, canMakeNoise:Bool){
    self.petName = petName
    self.noise = noise
    self.canMakeNoise = canMakeNoise
}

func eat(){
    println("\(self.petName) is eating...")
}

Thank you!

Upvotes: 0

Views: 2938

Answers (1)

ridvankucuk
ridvankucuk

Reputation: 2407

change this line:

var pet = Pets(petName: String, noise: String, canMakeNoise: Bool)

to this line:

var pet: Pets?

And after that you can create an instance of your Human class such as:

var human = Human(humanName: "chris", petName: "abc", noise: "hi", canMakeNoise: true)
var dog = Pets(petName: "erty", noise:"bark", canMakeNoise:true)
human.pet = dog

Upvotes: 3

Related Questions