3

I know Enum is used as below , what about Array or Dictionary?

enum VendingMachineError: Error {
  case invalidSelection
  case insufficientFunds(coinsNeeded: Int)
  case outOfStock
  }

throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
PPPPPPPPP
  • 660
  • 7
  • 14
  • Could you clarify the question? "what about Array or Dictionary" what about them?! what do you mean by this? – Ahmad F Oct 03 '18 at 08:06
  • I am asking, can we handle errors in swift with String or Array ? – PPPPPPPPP Oct 03 '18 at 08:10
  • This was my interview question , I am trying to share this we everyone to know the exact answer . I said no , the only way is Enum but I am not sure. – PPPPPPPPP Oct 03 '18 at 08:12
  • Try to give an example (maybe a pseudo-code) to let us what are you asking for/trying to achieve. – Ahmad F Oct 03 '18 at 08:12

1 Answers1

6

Any type conforming to the Error protocol can be used. If you really want to throw an array then it suffices to declare conformance to the protocol:

extension Array: Error {}

do {
    throw [1, 2, 3]
} catch {
    print("Failed:", error) // Failed: [1, 2, 3]
}

Here is more realistic example, using a struct to throw an error with additional information (a simplified example from Swift 3 errors with additional data):

struct ParserError: Error, LocalizedError {
    let line: Int

    public var errorDescription: String? {
        return "Parser error at line \(line)"
    }
}

func parse() throws {
    throw ParserError(line: 13)
}

do {
    try parse()
} catch let error {
    print(error.localizedDescription)
}

Output:

Parser error at line 13
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Is there a purpose of doing this? So, `error` would an array instead of -let's say- enum, correct? – Ahmad F Oct 03 '18 at 08:14
  • 2
    @AhmadF: Using an array is more a theoretical example, I do not see a real usage for that. I have added a link to a more realistic non-enum example. – Martin R Oct 03 '18 at 08:23