Reputation: 406
func add(numbers: Int...) -> Int?
{
var total:Int?
for i in numbers
{
total += i // >> 'int?' is not identical to 'Uint8' in swift
}
return total
}
numbers is Int, why total can't be assign to Int?
Upvotes: 2
Views: 257
Reputation: 130193
The error you're getting might be a little deceiving. The underlying issue here is that you declared a variable total
of type Int?
, but never actually assigned it a value. Since total
hasn't been given an integer value, it doesn't make sense to try to increment it by i
.
You can fix this by initializing the total
variable to zero. It's also worth noting that your total and return type do not need to be optionals here, since you're taking a variable number of non-optional Ints as input, meaning that your inputs will always have a total when added together.
If you're dead set on keeping optionals involved here, the following code will work.
func add(numbers: Int...) -> Int? {
var total: Int? = 0
for i in numbers {
total! += i
}
return total
}
Notice that the variable total
is being forcibly unwrapped on incrementation. This will crash if total is ever nil (i.e. not given an initial value). But this really isn't necessary. As I explained above, there is no need to use optionals here at all. Instead, I recommend implementing the function like this.
func add(numbers: Int...) -> Int {
var total = 0
for i in numbers {
total += i
}
return total
}
If you're interested in alternatives to your function that are perhaps more Swifty, you can rewrite your entire function like this:
func add(numbers: Int...) -> Int {
return reduce(numbers, 0, +)
}
Upvotes: 2
Reputation: 1714
Total is not Int
is Optional(Int)
, you have to unwrap for it to become Int
You can do this in 2 ways, faster and safer:
Faster: return total!
Safer:
if let total = total {return total}
Hope this helps, have fun with Swift!
Upvotes: 0
Reputation: 22343
Your code won't work anyway. You try to add a number to a variable you haven't initialized yet. So the return will always be nil
So change that:
var total:Int?
to that:
var total:Int? = 0
But you could also remove the ?
because it's not necessary, because you will take non-optional parameters.
var total:Int = 0
Upvotes: 0