0

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!

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply! I did var pet = pets? but now its complaining, "Expected member name or constructor call after type name"
Sorry i have edited my answer. You should use var pet: Pets?
it worked! thank you so much, been stuck here forever!
@MichaelNinh As it helped, please mark ridvankucuk's answer as correct (click the tick).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.