Reputation: 2650
I receive a type-related error ('Float' is not convertible to 'UInt8'
) while using the following formula in Swift. Although I've seen posts with similar questions, I can't seem to figure out why, in this case, the conversion to UInt8 is occurring in the first place and how to fix the type conversion error. I'm a newcomer to the language.
func compoundInterest (principal p: Float, interestRate r: Float,
timesCompounded n: Int, years t: Int) -> Float {
return p * pow(1 + (r / n), n * t)
}
compoundInterest(principal: 150, interestRate: 0.05, timesCompounded: 2, years: 10)
Upvotes: 0
Views: 2396
Reputation: 100632
The error message is misleading but the problem is that Swift doesn't do implicit type conversions — just to pull one part of your expression out:
r / n
r
is a floating point type. n
is an integer type. In C the promotion rules would implicitly concert n
to a float. That doesn't happen in Swift.
You probably want explicitly to cast all your integer types to Float
to resolve the issue.
Upvotes: 5