Day 16: Exceptions - String to Integer

  • + 2 comments

    A better approach would be:

    // ErrorType Protocol.
    enum ConversionError: ErrorType {
        case NotAnInt
    }
    
    // A function that "throws".
    func stringToInteger(stringValue: String) throws -> Int {
        guard Int(stringValue) != nil else {
            throw ConversionError.NotAnInt
        }
        return Int(stringValue)!
    }
    
    // Input.
    let inputString = readLine()!
    
    // Logic.
    do {
        try print(stringToInteger(inputString))
    } catch {
        print("Bad String")
    }
    

    But even that is not accepted.

    This exercise is broken for Swift.