Reputation: 11
I have two instances of almost the same code, one works and the other doesn’t.
Working through Apple’s Intro to App Development with Swift I’ve reached a point where I’m supposed to make an array, write a function that gives at least two responses to the data in the array, and then write a for...in
loop that goes through it and gives the correct response to each value in the array. I keep getting this error:
Binary operator ‘>=‘ cannot be applied to two ‘[Int]’ operands error.
But, if I put the for...in
loop inside the function everything works.
func goal(time:[Int]) {
for code in time {
if (code >= 90) {
print ("Good Bunny, Have a carrot!")
}else {
print ("Bad Rabbit! Try Harder!")
}
}
}
goal(time: codeLearned)
func bunny(bun: [Int]){
if (bun >= [90]) {
print ("Good Bunny")
} else {
print ("Bad Rabbit")
}
}
bunny(bun: codeLearned)
With the function that contains the loop, putting the if
in brackets ()
fixed the error, but that isn’t working without the loop, and since the exercise is to do it without the loop that’s what I want to do.
Upvotes: 0
Views: 51
Reputation: 3514
They don't have the same logic. The first function checks the value of the element in the array, the second tries to compare the given array with a single-element array.
func goal(time:[Int]) {
for code in time {
if (code >= 90) {
print ("Good Bunny, Have a carrot!")
} else {
print ("Bad Rabbit! Try Harder!")
}
}
}
goal(time: codeLearned)
/// If your goal is the check count of array
func bunny(bun: [Int]){
if (bun.count >= 90) {
print ("Good Bunny")
} else {
print ("Bad Rabbit")
}
}
bunny(bun: codeLearned)
/// If your goal is the check element value in array
func bunny(bun: [Int]){
for item in bun {
if (item >= 90) {
print ("Good Bunny")
} else {
print ("Bad Rabbit")
}
}
}
bunny(bun: codeLearned)
Upvotes: 1