🕰 未来
Future
仅代表一些可能需要一些时间才能完成的工作(或者不)。
Futures 的力量在于它们可以被串联在一起,产生一个包含所有组件 Futures 工作的单一 Future 对象。
此外,这种 Future 的工作实际上在你运行 future 之前不会完成。
以下是一个使用 Future 可以实现复杂逻辑的示例:
struct User: Codable {
var id: String
var name: String
}
struct Food: Codable {
var type: String
var tastiness: Int
}
// Make a future that loads a user value from the file "User.json"
let loadFileUser: FutureResult<User> = Bundle.main
.loadData(forResource: "User.json")
.flatMapResult(User.decodeJSON(from:))
// Make a future that loads food value from the json string
let loadStringFood: FutureResult<Food> = Future<String>
.init(value: #"{ "type": "curry", "tastiness": 1000 }"#)
.map({ $0.data(using: .utf8)! })
.flatMap(Food.decodeFutureJSON(from:))
// Make a future that loads another user value from a network request
let loadNetworkUser: FutureResult<User> = URLSession.shared
.dataTaskFutureResult(with: URLRequest(url: URL(string: "https://foo.bar")!))
.mapResult({ $0.data })
.flatMapResult(User.decodeFutureJSON(from:))
// zip the 3 futures together and, if all successful, convert the response into a string.
let combinedFuture = zipResult3With(
loadStringFood,
loadFileUser,
loadNetworkUser
) { (food: $0, user: $1, networkUser: $2) }
.mapResult({
"\($0.user.name) likes \($0.food.type) x\($0.food.tastiness)... networkUser: '\($0.networkUser.name)'"
})
// once it is finally run, print the result
combinedFuture.run { result in
print(result)
}
未来改进领域
- FutureOptional - 添加测试和类似于
Future
的功能>> - 可取消 - 以某种方式允许 Futures 提供可取消令牌。
- 更多实用扩展
UIImageView().setImage(Future
()) CLGeocoder().geocode(...) -> FutureResult<[CLPlacemark]>
- 也许
CLLocationManager
... 如何处理代理?我想 Future 不适合事件流,但是有时候我们需要 1 次代理调用。