Skip to content

Instantly share code, notes, and snippets.

@BasThomas
Created September 11, 2021 14:21
Show Gist options
  • Save BasThomas/ebf246686d23cf07b6ee2b00454d2d34 to your computer and use it in GitHub Desktop.
Save BasThomas/ebf246686d23cf07b6ee2b00454d2d34 to your computer and use it in GitHub Desktop.
import Foundation
import XCTest
struct WompWomp: Error {
}
func myThrowingFunction() throws -> Int {
throw WompWomp()
}
func myClosureFunction(_ closure: () -> Void) {
closure()
}
class ThrowNoThrowTests: XCTestCase {
func testExample() {
myClosureFunction {
XCTAssertEqual(myThrowingFunction(), 1) // Error: Call can throw but is not marked with 'try'
}
}
func testExample2() {
myClosureFunction { // Error: Invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'
XCTAssertEqual(try myThrowingFunction(), 1)
}
}
func testExample3() {
myClosureFunction {
do {
try XCTAssertEqual(myThrowingFunction(), 1) // Test result: XCTAssertEqual failed: threw error "WompWomp()"
} catch { // Warning: 'catch' block is unreachable because no errors are thrown in 'do' block
print(error.localizedDescription)
}
}
}
}
@liamnichols
Copy link

liamnichols commented Sep 11, 2021

Maybe these examples also help:

extension ThrowNoThrowTests {
    func testExample4() {
        myClosureFunction {
            do {
                try XCTAssertEqualWithoutAutoclosure(myThrowingFunction(), 1)
            } catch {
                print(error.localizedDescription) // The operation couldn’t be completed. (__lldb_expr_14.WompWomp error 1.)
            }
        }
    }

    func testExample5() {
        myClosureFunction {
            XCTAssertEqualWithClosure({ try myThrowingFunction() }, { 1 }) // Test result: XCTAssertEqual failed: threw error "WompWomp()"
        }
    }
}

func XCTAssertEqualWithoutAutoclosure<T: Equatable>(_ lhs: T, _ rhs: T) {
    XCTAssertEqual(lhs, rhs)
}

func XCTAssertEqualWithClosure<T: Equatable>(_ lhs: () throws -> T, _ rhs: () throws -> T) {
    XCTAssertEqual(try lhs(), try rhs())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment