gpt4 book ai didi

swift - 为什么 Xcode 一直用 '_' 替换泛型

转载 作者:可可西里 更新时间:2023-11-01 01:07:21 26 4
gpt4 key购买 nike

我正在使用 Swift 5 和 Vapor 3 创建一个服务器。在设置路由时,我想从我的 Controller 调用一个函数,该函数返回一个可选值,如下所示:

//Person.swift

struct Person: Content {
...
}
//PersonController.swift

func update(_ request: Request) throws -> Future<Person> {
let uuid = try request.parameters.next(UUID.self)

return try request.content.decode(Person.self).flatMap { content in
request.withPooledConnection(to: DatabaseIdentifier<PostgreSQLDatabase>.psql) { connection in
/*
* No code completion beyond this point,
* even connection appears as type '_' instead of
* PostgreSQLConnection (not relevant to the question tho,
* just worth noting)
*/
if content.lastName != nil {
return connection.raw("Very long SQL query...")
.binds([...])
.first(decoding: Person.self)
}

return connection.raw("Other long SQL query")
.binds([...])
.first(decoding: Person.self)
}
}

}
router.put("people", UUID.parameter, use: personController.update)

但是我得到了这个错误

Cannot convert value of type '(Request) throws -> EventLoopFuture<Person?>' to expected argument type '(Request) throws -> _'

我在使用 Vapor 时看到很多情况,其中 Xcode 只是放弃自动完成,所有内容都被键入为 _ .主要在用作回调的闭包内。这非常烦人,坦率地说,我不确定它是由 Vapor、Swift 还是 Xcode 引起的。这是一个巨大的 PITA,但一旦我编译,它就会得到解决,类型就会被整理出来。然而,在这种情况下,它根本不起作用。

所以问题是:为什么 Xcode 说预期的类型是 (Request) throws -> _Request.put(_:use:) 的实际定义时需要 (Request) throws -> T这对 T 有何影响?正在Future<Person>Future<Person?>

最佳答案

.first您在这里调用的方法:

return connection.raw("Other long SQL query")
.binds([...])
.first(decoding: Person.self)

返回 Future<Optional<Person>> , 或 Future<Person?> .您路由处理程序的返回类型是 Future<Person> ,所以你的返回类型不正确。但即使您确实更改了处理程序的返回类型,也无法解决问题。

你的主要问题是你不能从路由处理程序返回一个可选的,因为绝不是 Optional曾经符合 ResponseEncodable .如果需要,您可以自己添加一致性。

如果你不想添加一致性,你可以只使用 .unwrap(or:)解码查询结果后的方法:

return connection.raw("Other long SQL query")
.binds([...])
.first(decoding: Person.self)
.unwrap(or: Abort(.notFound))

这将检查将来的值是否存在。如果是,则传递该值。否则, future 链会收到您传入的错误,并将返回该错误。

关于swift - 为什么 Xcode 一直用 '_' 替换泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55755667/

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