swiftswift-optionals

Is there a way to embed an assertionFailure into '??' expression?


TimeZone(abbreviation: "GMT+1") ?? TimeZone.current

If you want to have a non optional and assert before TimeZone.current fallback is used after ?? what syntax would I use in swift?

something like this

TimeZone(abbreviation: "GMT+1") ?? (assertionFailure("what weird runtime have you've got????"), TimeZone.current)

(which obviously does not compile)


Solution

  • Try to write extension for Optional where you can handle your case, for example:

    extension Optional {
        func rescue(
            _ assertion: String, 
            _ fallback: Wrapped
        ) -> Wrapped {
            guard case let .some(value) = self else {
                assertionFailure(assertion)
                return fallback
            }
            
            return value
        }
    }
    
    TimeZone(abbreviation: "GMT+1").rescue("what weird runtime have you've got????", .current) // GMT+0100
    TimeZone(abbreviation: "GMT+1lalala").rescue("what weird runtime have you've got????", .current) // what weird runtime have you've got????