1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 - 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A value that represents either a success or a failure, including an
/// associated value in each case.
@frozen
public enum Result<Success: ~Copyable, Failure: Error> {
/// A success, storing a `Success` value.
case success(Success)
/// A failure, storing a `Failure` value.
case failure(Failure)
}
extension Result: Copyable where Success: Copyable {}
extension Result: Sendable where Success: Sendable & ~Copyable {}
extension Result: Equatable where Success: Equatable, Failure: Equatable {}
extension Result: Hashable where Success: Hashable, Failure: Hashable {}
extension Result {
/// Returns a new result, mapping any success value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a success. The following example transforms
/// the integer success value of a result into a string:
///
/// func getNextInteger() -> Result<Int, Error> { /* ... */ }
///
/// let integerResult = getNextInteger()
/// // integerResult == .success(5)
/// let stringResult = integerResult.map { String($0) }
/// // stringResult == .success("5")
///
/// - Parameter transform: A closure that takes the success value of this
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new success value if this instance represents a success.
@_alwaysEmitIntoClient
@_disfavoredOverload // FIXME: Workaround for source compat issue with
// functions that used to shadow the original map
// (rdar://125016028)
public func map<NewSuccess: ~Copyable>(
_ transform: (Success) -> NewSuccess
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return .success(transform(success))
case let .failure(failure):
return .failure(failure)
}
}
@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)
@_silgen_name("$ss6ResultO3mapyAByqd__q_Gqd__xXElF")
@usableFromInline
internal func __abi_map<NewSuccess>(
_ transform: (Success) -> NewSuccess
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return .success(transform(success))
case let .failure(failure):
return .failure(failure)
}
}
}
@_disallowFeatureSuppression(NoncopyableGenerics)
extension Result where Success: ~Copyable {
// FIXME(NCG): Make this public.
@_alwaysEmitIntoClient
public consuming func _consumingMap<NewSuccess: ~Copyable>(
_ transform: (consuming Success) -> NewSuccess
) -> Result<NewSuccess, Failure> {
switch consume self {
case let .success(success):
return .success(transform(consume success))
case let .failure(failure):
return .failure(consume failure)
}
}
// FIXME(NCG): Make this public.
@_alwaysEmitIntoClient
public borrowing func _borrowingMap<NewSuccess: ~Copyable>(
_ transform: (borrowing Success) -> NewSuccess
) -> Result<NewSuccess, Failure> {
switch self {
case .success(let success):
return .success(transform(success))
case let .failure(failure):
return .failure(failure)
}
}
}
extension Result where Success: ~Copyable {
/// Returns a new result, mapping any failure value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a failure. The following example transforms
/// the error value of a result by wrapping it in a custom `Error` type:
///
/// struct DatedError: Error {
/// var error: Error
/// var date: Date
///
/// init(_ error: Error) {
/// self.error = error
/// self.date = Date()
/// }
/// }
///
/// let result: Result<Int, Error> = // ...
/// // result == .failure(<error value>)
/// let resultWithDatedError = result.mapError { DatedError($0) }
/// // result == .failure(DatedError(error: <error value>, date: <date>))
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new failure value if this instance represents a failure.
@_alwaysEmitIntoClient
public consuming func mapError<NewFailure>(
_ transform: (Failure) -> NewFailure
) -> Result<Success, NewFailure> {
switch consume self {
case let .success(success):
return .success(consume success)
case let .failure(failure):
return .failure(transform(failure))
}
}
}
@_disallowFeatureSuppression(NoncopyableGenerics)
extension Result {
@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)
@usableFromInline
internal func mapError<NewFailure>(
_ transform: (Failure) -> NewFailure
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return .failure(transform(failure))
}
}
}
extension Result {
/// Returns a new result, mapping any success value using the given
/// transformation and unwrapping the produced result.
///
/// Use this method to avoid a nested result when your transformation
/// produces another `Result` type.
///
/// In this example, note the difference in the result of using `map` and
/// `flatMap` with a transformation that returns an result type.
///
/// func getNextInteger() -> Result<Int, Error> {
/// .success(4)
/// }
/// func getNextAfterInteger(_ n: Int) -> Result<Int, Error> {
/// .success(n + 1)
/// }
///
/// let result = getNextInteger().map { getNextAfterInteger($0) }
/// // result == .success(.success(5))
///
/// let result = getNextInteger().flatMap { getNextAfterInteger($0) }
/// // result == .success(5)
///
/// - Parameter transform: A closure that takes the success value of the
/// instance.
/// - Returns: A `Result` instance, either from the closure or the previous
/// `.failure`.
@_alwaysEmitIntoClient
@_disfavoredOverload // FIXME: Workaround for source compat issue with
// functions that used to shadow the original flatMap
// (rdar://125016028)
public func flatMap<NewSuccess: ~Copyable>(
_ transform: (Success) -> Result<NewSuccess, Failure>
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return transform(success)
case let .failure(failure):
return .failure(failure)
}
}
@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)
@_silgen_name("$ss6ResultO7flatMapyAByqd__q_GADxXElF")
@usableFromInline
internal func __abi_flatMap<NewSuccess>(
_ transform: (Success) -> Result<NewSuccess, Failure>
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return transform(success)
case let .failure(failure):
return .failure(failure)
}
}
}
@_disallowFeatureSuppression(NoncopyableGenerics)
extension Result where Success: ~Copyable {
// FIXME(NCG): Make this public.
@_alwaysEmitIntoClient
public consuming func _consumingFlatMap<NewSuccess: ~Copyable>(
_ transform: (consuming Success) -> Result<NewSuccess, Failure>
) -> Result<NewSuccess, Failure> {
switch consume self {
case let .success(success):
return transform(consume success)
case let .failure(failure):
return .failure(failure)
}
}
// FIXME(NCG): Make this public.
@_alwaysEmitIntoClient
public borrowing func _borrowingFlatMap<NewSuccess: ~Copyable>(
_ transform: (borrowing Success) -> Result<NewSuccess, Failure>
) -> Result<NewSuccess, Failure> {
switch self {
case .success(let success):
return transform(success)
case let .failure(failure):
return .failure(failure)
}
}
}
extension Result where Success: ~Copyable {
/// Returns a new result, mapping any failure value using the given
/// transformation and unwrapping the produced result.
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance, either from the closure or the previous
/// `.success`.
@_alwaysEmitIntoClient
public consuming func flatMapError<NewFailure>(
_ transform: (Failure) -> Result<Success, NewFailure>
) -> Result<Success, NewFailure> {
switch consume self {
case let .success(success):
return .success(success)
case let .failure(failure):
return transform(failure)
}
}
}
extension Result {
@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)
@_silgen_name("$ss6ResultO12flatMapErroryAByxqd__GADq_XEs0D0Rd__lF")
@usableFromInline
internal func __abi_flatMapError<NewFailure>(
_ transform: (Failure) -> Result<Success, NewFailure>
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return transform(failure)
}
}
}
extension Result where Success: ~Copyable {
/// Returns the success value as a throwing expression.
///
/// Use this method to retrieve the value of this result if it represents a
/// success, or to catch the value if it represents a failure.
///
/// let integerResult: Result<Int, Error> = .success(5)
/// do {
/// let value = try integerResult.get()
/// print("The value is \(value).")
/// } catch {
/// print("Error retrieving the value: \(error)")
/// }
/// // Prints "The value is 5."
///
/// - Returns: The success value, if the instance represents a success.
/// - Throws: The failure value, if the instance represents a failure.
@_alwaysEmitIntoClient
public consuming func get() throws(Failure) -> Success {
switch consume self {
case let .success(success):
return success
case let .failure(failure):
throw failure
}
}
}
extension Result where Success: ~Copyable {
/// Creates a new result by evaluating a throwing closure, capturing the
/// returned value as a success, or any thrown error as a failure.
///
/// - Parameter body: A potentially throwing closure to evaluate.
@_alwaysEmitIntoClient
public init(catching body: () throws(Failure) -> Success) {
do {
self = .success(try body())
} catch {
self = .failure(error)
}
}
}
extension Result {
/// ABI: Historical get() throws
@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)
@_silgen_name("$ss6ResultO3getxyKF")
@usableFromInline
func __abi_get() throws -> Success {
switch self {
case let .success(success):
return success
case let .failure(failure):
throw failure
}
}
}
extension Result where Failure == Swift.Error {
/// ABI: Historical init(catching:)
@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)
@_silgen_name("$ss6ResultOss5Error_pRs_rlE8catchingAByxsAC_pGxyKXE_tcfC")
@usableFromInline
init(__abi_catching body: () throws(Failure) -> Success) {
do {
self = .success(try body())
} catch {
self = .failure(error)
}
}
}
|