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

标签 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)

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

如何编译它?这可能吗?

最佳答案

我“解决”了它。这有点像黑客。但它确实完成了工作

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)
            }
        }
    }
}

关于ios - 如何在 swift 3 中专门化通用高阶函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41258882/

相关文章:

ios - 更改 UILabel 文本会出现延迟,但为什么呢?

ios - 弹出窗口中的 uiBarButtonItem 框架最佳选择

java - 为什么我的代码在java中输出package.class@letternumbers?

ios - 如何让数据管理器告诉 View Controller 重新加载集合

mysql - SQL |获取产品和产品变体

java - 什么时候到 'IN' 什么时候不到?

ios - 重新加载数据时 CollectionView 闪烁

ios - 如何从 UISegmentController 中删除边框?

ios - 重用 UITableView 中的单元格

ios - 在 xcode 12 中创建通用框架时出现 Lipo 错误