TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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
            break
        } else if testNumber < 100 {
            continue
        } 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?

2      

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

2      

So i cannot make an empty string?

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your 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.