let a = 4let b: Int32 = 100let c: UInt8 = 12It seems that we cannot add or minus when the variables are mixed types.

So what"s the result of this problem?

You are watching: The sum of a and b


Swift disallows mathematical operations between different numeric types. Writing:

let result = a + b - c // error...is an error. Unless you have specific requirements, like all the operands are non-negative, the rule of thumb is to convert everything to the widest data type, in this case Int:

let result = a + Int(b) - Int(c) // 92


For a complete answer I would say

"Swift does not allow you to do math with different mathematical types. The expression a+b-c will throw an error, so we need to cast all the values to the same type:

let result = a+Int(b)-Int(c)"

(As Code Different says in their answer, you should "promote" values to the widest/richest type e.g. from smaller integer types to larger, from unsigned to signed, or from integer to floating point if any of the values are floating point.)


Thanks for contributing an answer to Stack Overflow!

Please be sure to answer the question. Provide details and share your research!

But avoid

Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged swift or ask your own question.


site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev2021.9.28.40331

See more: Where To Get Super Rod In Omega Ruby, Where To Get Super Rod In Pokemon Omega Ruby

Stack Overflow works best with JavaScript enabled

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.