Files
purchases-ios/Sources/FoundationExtensions/Result+Extensions.swift
T
NachoSoto 294212fed1 Result.init(value:error:): avoid creating error if value is provided (#1672)
Our implementation of `ErrorUtils.error(with:message:underlyingError:extraUserInfo:)` always calls `ErrorUtils.logErrorIfNeeded`, this means that even though the error wasn't actually used, it was being logged as if it had occurred.
By using `@autoclosure` we avoid this and instead create it lazily.

This incorrect logging lead to [CSDK-112], which won't be confusing anymore.

[CSDK-112]: https://revenuecats.atlassian.net/browse/CSDK-112?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
2022-06-08 11:54:06 -07:00

61 lines
1.6 KiB
Swift

//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// Result+Extensions.swift
//
// Created by Nacho Soto on 12/1/21.
extension Result {
/// Creates a `Result` from either a value or an error.
/// This is useful for converting from old Objective-C closures to new APIs.
init( _ value: Success?, _ error: @autoclosure () -> Failure?, file: StaticString = #fileID, line: UInt = #line) {
if let value = value {
self = .success(value)
} else if let error = error() {
self = .failure(error)
} else {
fatalError("Unexpected nil value and nil error", file: file, line: line)
}
}
var value: Success? {
switch self {
case let .success(value): return value
case .failure: return nil
}
}
var error: Failure? {
switch self {
case .success: return nil
case let .failure(error): return error
}
}
}
extension Result where Success: OptionalType {
/// Converts a `Result<Success?, Error>` into `Result<Success, Error>?`
var asOptionalResult: Result<Success.Wrapped, Failure>? {
switch self {
case let .success(optional):
if let value = optional.asOptional {
return .success(value)
} else {
return nil
}
case let .failure(error):
return .failure(error)
}
}
}