Reputation: 23
I am just playing around with Swift for the first time and I do not understand why this does not work. Any help would be great!
I get the error could not find an overload for '-' that accepts the supplied arguments
for the line that says self.health = self.health - amount
class human {
var name:String
var height:Integer
var hairColor:String
var health:Integer
init(name:String, height:Integer, hairColor:String) {
self.name = name
self.height = height
self.hairColor = hairColor
self.health = 100
}
func applyDamage(amount:Integer) -> Integer{
self.health = self.health - amount
return self.health
}
}
Thank you!
Upvotes: 2
Views: 3216
Reputation: 71
For what it is worth, you might want to do
self.health -= amount
instead of
self.health = self.health - amount
to be more idiomatic
Upvotes: 2
Reputation: 7695
To explain the actual error message, Swift is trying to apply the '-' operator to an Integer and an Integer, but you have not overloaded the '-' operator. This is why the error is worded as it is. The '-' operators works in the case of an Int and an Int, which was obviously your intention in this instance, so you simply need to use Int instead of Integer
Upvotes: 3
Reputation: 64694
I think you may have meant to use Int instead of Integer. This code works fine:
class human {
var name:String
var height:Int
var hairColor:String
var health:Int
init(name:String, height:Int, hairColor:String) {
self.name = name
self.height = height
self.hairColor = hairColor
self.health = 100
}
func applyDamage(amount:Int) -> Int{
self.health = self.health - amount
return self.health
}
}
Upvotes: 0