Reputation: 143
I am new to programming in Swift and I am taking a basic online course to teach me the syntax. On one of the courses on classes, it asked me to do this:
2a. Add a type property to the Peach class called "varieties". It should hold an array of different types of peaches.
2b. Add an instance method called ripen() that increases the value of the stored property, softness, and returns a string indicating whether the peach is ripe.
2c. Create an instance of the Peach class and call the method ripen().
It's not that hard. For the ripen function, I decided to use a switch control statement, with 3 being the optimal ripeness, 1 and 2 being too hard, 4 and 5 being overripe.
class Peach {
let variety: String
static let varieties = ["Bonita", "Cardinal", "Frost", "Golden"]
var softness: Int
init(variety: String, softness: Int) {
self.variety = variety
self.softness = 0
}
func ripen(softness: Int) -> String {
softness ++
switch softness {
case 1, 2 :
return "Not ready yet"
case 3:
return "Ripe"
case 4,5:
return "Over ripe"
default:
return "Gross"
}
}
}
On the line with the switch, this returns the error: Expected expression after operator. Looking at the color formatting, it appears that my code isn't treating the variable properly. So, how do I fix this error and what exactly does it mean? I'm sure this is a simple error that only a beginner would make, so I appreciate your patience in helping me.
Upvotes: 0
Views: 64
Reputation: 437372
The problem starts with softness ++
. You have to get rid of that space. But when you do that, it's going to complain that softness
parameter to ripen
is immutable. You probably should just remove the parameter to ripen
, in which case it will know you wanted to increment the softness
property.
class Peach {
let variety: String
static let varieties = ["Bonita", "Cardinal", "Frost", "Golden"]
var softness: Int
init(variety: String, softness: Int) {
self.variety = variety
self.softness = 0
}
func ripen() -> String {
softness++
switch softness {
case 1, 2 :
return "Not ready yet"
case 3:
return "Ripe"
case 4,5:
return "Over ripe"
default:
return "Gross"
}
}
}
Personally, I might be inclined to define variety
as an enum
:
class Peach {
enum Variety {
case Bonita
case Cardinal
case Frost
case Golden
}
let variety: Variety
var softness: Int
init(variety: Variety, softness: Int) {
self.variety = variety
self.softness = 0
}
...
}
Upvotes: 1