简体   繁体   中英

'Float' is not convertible to 'UInt8' in Swift

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM