# Checkpoint 4

Paul Hudson    @twostraws

Updated for Xcode 13.3

With functions under your belt, it’s time to try a little coding challenge. Don’t worry, it’s not that hard, but it might take you a while to think about and come up with something. As always I’ll be giving you some hints if you need them.

The challenge is this: write a function that accepts an integer from 1 through 10,000, and returns the integer square root of that number. That sounds easy, but there are some catches:

1. You can’t use Swift’s built-in `sqrt()` function or similar – you need to find the square root yourself.
2. If the number is less than 1 or greater than 10,000 you should throw an “out of bounds” error.
3. You should only consider integer square roots – don’t worry about the square root of 3 being 1.732, for example.
4. If you can’t find the square root, throw a “no root” error.

As a reminder, if you have number X, the square root of X will be another number that, when multiplied by itself, gives X. So, the square root of 9 is 3, because 3x3 is 9, and the square root of 25 is 5, because 5x5 is 25.

I’ll give you some hints in a moment, but as always I encourage you to try it yourself first – struggling to remember how things work, and often having to look them up again, is a powerful way to make progress.

Hacking with Swift+ subscribers can get a complete video solution for this checkpoint here: Solution to Checkpoint 4. If you don’t already subscribe, you can start a free trial today.

Still here? Okay, here are some hints:

• This is a problem you should “brute force” – create a loop with multiplications inside, looking for the integer you were passed in.
• The square root of 10,000 – the largest number I want you to handle – is 100, so your loop should stop there.
• If you reach the end of your loop without finding a match, throw the “no root” error.
• You can define different out of bounds errors for “less than 1” and “greater than 10,000” if you want, but it’s not really necessary – just having one is fine.

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Sponsor Hacking with Swift and reach the world's largest Swift community!