UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

I am learning Swift

Forums > Swift

I am at checkpoint 4 and i got some question. and this is my code:

import Cocoa

enum error: Error {
    case outOfBounds, noRoot

func squareRoot(of number: Int) throws -> Int {

    var myAnswer: Int

    if number > 10000 || number < 1 {
        throw error.outOfBounds

    for testNumber in 1...101 {
        var answerNumber = testNumber * testNumber
        if answerNumber == number {
            myAnswer = testNumber
        } else if testNumber < 100 {
        } else {
            throw error.noRoot

    return myAnswer


do {
    try print("the square root is \(squareRoot(of: 9))")
} catch error.outOfBounds {
    print("it is out of bounds")
} catch error.noRoot {
    print("it has no root")

I get the warning said that "Variable 'myAnswer' used before being initialized" But when i change this:

var myAnswer: Int = 0

there is no more warning message. So where i did it wrong?


You are setting an inital value in the var myAnswer: Int = 0 thereby initializing it.


So i cannot make an empty string?


Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.