GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

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.