gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:48:54 25 4
gpt4 key购买 nike

我正在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com