DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 8/100)

Swift

  • functions with throw Exceptions
import Cocoa

enum PasswordError: Error, LocalizedError {
    case TooShort
    case Obvious

    var errorDescription: String? {
        switch self {
        case .TooShort:
            return NSLocalizedString("Password is too short", comment: "Too short")
        case .Obvious:
            return NSLocalizedString("Password is too obvious", comment: "Obvious")
        }
    }
}

// although defined with `throws`,
// this function doesn't have to throw an exception
func checkPassword(_ pwd: String) throws -> Bool {
    if pwd.count < 6 {
        throw PasswordError.TooShort
    }
    if pwd == "123456" {
        throw PasswordError.Obvious
    }
    return true
}

do {
    let ok = try checkPassword("hello")
    print(ok)
} catch {
    print("Error happened: \(error.localizedDescription)")
}

// ## Checkpoints

/*
 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:

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

enum RootError: Error, LocalizedError {
    case outOfBounds
    case noRoot

    var errorDescription: String? {
        switch self {
        case .outOfBounds:
            return NSLocalizedString("Out of Bounds", comment: "OOB")
        case .noRoot:
            return NSLocalizedString("No root", comment: "NR")
        }
    }
}

func sqroot(_ num: Int) throws -> Int {
    if num < 1 || num > 10_000 {
        throw RootError.outOfBounds
    }
    for i in 1...100 {
        if i * i == num {
            return i
        }
    }
    throw RootError.noRoot
}

do {
    print(try sqroot(9))
    print(try sqroot(25))
    print(try sqroot(37))
} catch {
    print("error happened: \(error.localizedDescription)")
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)