0

The code is written in Swift 2.0. I am doing a little tinkering project for clash of clans. My code is below.

enum Resource {
    case gold
    case elixer
    case darkElixer
}

class Avatar {
    var cost, health, damage, space: Int
    var costType: Resource
    init(damage: Int, health: Int, cost: Int, costType: Resource, space: Int){
        self.damage = damage
        self.health = health
        self.cost = cost
        self.costType = costType
        self.space = space
    }
}

class Barbarian: Avatar {
    init() {
        super.init(damage: 44, health: 110, cost: 200, costType: .elixer, space: 1)
    }
}

class Archer: Avatar {
    init() {
        super.init(damage: 22, health: 44, cost: 400, costType: .elixer, space: 1)
    }
}

I am trying this function.

func troopCost(troop: Avatar, quantity: Int) -> (Int, Resource){
    let rResource = troop.costType
    let rCost = troop.cost * quantity
    return (rCost, rResource)
}

When I call the function like this.

troopCost(Barbarian, quantity: 2)

I get this error.

Cannon invoke 'troopCost' with an argument list of type '(Barbarian.Type, quantity: Int)'

1 Answer 1

4

When you say troopCost(Barbarian, quantity: 2), you are trying to pass the Barbarian class itself as the argument.

But your function takes an Avatar instance. So you must first create an instance.

let troop = Barbarian()
troopCost(troop, quantity: 2)

Furthermore, you could make troopCost into an method on Avatar:

class Avatar {
    // ...
    func cost(quantity: Int) -> (Int, Resource) {
        return (cost * quantity, costType)
    }
}

let troop = Barbarian()
troop.cost(quantity: 2)

And if you make these into structs instead of classes, you won't have to write out that long init method yourself ;)

Sign up to request clarification or add additional context in comments.

4 Comments

thanks man that was such an easy fix I don't know why I didn't think of that.
@CodyWeaver if this answered your question, please accept the answer :)
how do you accept an answer? Also how would I make them into structs?
Simply use struct instead of class. More info here. Click the checkmark on the left to accept. You should also go back through your old questions and accept answers if appropriate. More info here.

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.