Pattern Matching on Swift Error Codes
I was wondering why this shorter syntax works. Is there some special compiler magic for pattern matching against error codes of
NSError
instances? Turns out: no, the answer is much simpler. Foundation includes an overload for the pattern matching operator~=
that matches error values against error codes.The implementation looks something like this:
public func ~= (code: CocoaError.Code, error: any Error) -> Bool { guard let error = error as? CocoaError else { return false } return error.code == code }
However, my experience has been that this only works for concrete types, not when your errors or codes use a protocol.
Previously:
Update (2023-03-15): See also: Rob Jonson.
Update (2023-03-16): The problem seems to be this bug (via Rob Jonson).