Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Basics (retired) Operators Operator Precedence

Why is 3 % 7 = 3? How did Swift calculate that?

Im not sure how swift calculated that. I get 7 % 3 = 1

But not sure how it calculates (shown in the video) 3 % 7 = 3

2 Answers

I could be wrong since I am still somewhat of a novice, however if it works the way I understand it, then modulus returns the remainder of a division operation. Since 7 will not got into 3, the answer is 0 and you are left with 3. Again this is just my understanding. Hope that it was helpful.

Tommy Choe
Tommy Choe
38,156 Points

Hey Jeffrey,

that's a great question. I didn't know either so I did some basic testing to find an answer.

I kept switching a and b to see what the result would be. So it appears that the built-in modulus operator can't handle a particular case where 'a' is less than 'b' so it simply returns 'a'.

var a = 5
var b = 10000
var c = a % b
print(c)
//answer is 5

You can try this out on the Xcode playground to see it for yourself if you want.

Anyways hope that helps!