![](/img/trans.png)
[英]Swift generics - Cannot explicitly specialize a generic function
[英]How do I specialize generic higher order function in swift 3?
我很快就將一些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) -> ()'
我該如何進行編譯? 可能嗎?
我“解決”了。 這是一種hack。 但這確實起作用
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)
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.