Reputation: 21
I'm brand new to Swift and I'm toying around trying to build a simple program that will tell the user what year of the Chinese calendar they were born in based on their age.
var string1 = "You are year of the"
let age:Int? = Int(ageField.text!)
if age <= 12 {
let remainder = age!
} else {
let remainder = age! % 12
}
if remainder == 0 {
string1 += " sheep."
}; if remainder == 1 {
string1 += " horse."
}; if remainder == 2 {
string1 += " snake."
}; if remainder == 3 { // And so on and so forth...
I get an error message on each "if" line that says the binary operator '==' cannot be applied to the operands of type '_' and 'Int'. Any ideas what I can do to solve this problem?
Upvotes: 1
Views: 845
Reputation: 285280
As a summary of Alessandro's answer and the comments your optimized code could look like
var string1 = "You are year of the"
if let age = Int(ageField.text!) {
let remainder = age % 12
if remainder == 0 {
string1 += " sheep."
} else if remainder == 1 {
string1 += " horse."
} else if remainder == 2 {
string1 += " snake."
} // And so on and so forth...
} else {
print("please enter a number")
}
or a bit "swiftier" using a switch
statement
var string1 = "You are year of the "
if let age = Int(ageField.text!) {
switch age % 12 {
case 0: string1 += "sheep."
case 1: string1 += "horse."
case 2: string1 += "snake."
// And so on and so forth...
}
} else {
print("please enter a number")
}
PS: actually the sheep is a goat ;-)
Upvotes: 2
Reputation: 1589
the variable/constants remainder
should be declared outside the if
construct and also you can remove the character ";" in your code. Swift does not need ";" at the end of instruction like objective-c
Upvotes: 2