如何在swift 3中专门化通用高阶函数?

时间:2016-12-21 09:07:05

标签: ios swift performance unit-testing asynchronous

我在swift中使用了一些http代码。在我的测试课中,我有以下功能:

func measureAsync<T>(_ block: @escaping ((Result<T>) -> Void) -> ()) {
    self.measure {
        let expect = self.expectation(description: "get from backend")
        block { (result) in
            expect.fulfill()
            XCTAssertNotNil(result.value, "value")
        }

        self.waitForExpectations(timeout: 10) { (error) in
            if let error = error {
                print("error", error)
            }
        }
    }
}

public func curry<A, B, C>(_ f : @escaping (A, B) -> C) -> (A) -> (B) -> C {
    return { (a : A) -> (B) -> C in
        { (b : B) -> C in
            f(a, b)
        }
    }
}

我试图在我的测试用例中调用这个函数:

    let block = curry(StorageClient.client.getProfilePicture)(URL.init(fileURLWithPath: "/User Photos/profile_MThumb.jpg"))
    measureAsync(block)

我得到编译器错误&#34;无法将类型'((Result<UIImage>) -> Void) -> ()'的值转换为预期的参数类型'((Result<_>) -> Void) -> ()'

如何编译?它甚至可能吗?

1 个答案:

答案 0 :(得分:0)

我&#34;解决了&#34;它。这是一种黑客攻击。但它完成了这项工作

func testProfilePicture() {
    let block = curry(StorageClient.client.getProfilePicture)(URL.init(fileURLWithPath: "/User Photos/profile_MThumb.jpg"))
    measureAsync(UIImage.self, block)
}

func measureAsync<T>(_ type: T.Type, _ block: Any) {
    self.measure {
        let expect = self.expectation(description: "get from backend")
        if let block = block as? (((Result<T>) -> Void) -> Void) {
            block { (result: Result<T>) in
                expect.fulfill()
                XCTAssertNotNil(result.value, "value is nil")
            }
        } else {
            fatalError("could not downcast block")
        }

        self.waitForExpectations(timeout: 10) { (error) in
            if let error = error {
                print("error", error)
            }
        }
    }
}