Compare commits

...

15 Commits

Author SHA1 Message Date
Caleb Kleveter a3d86b2ba7
Updated error handling for Failable instances tests 2019-06-05 10:01:59 -05:00
Caleb Kleveter 012fcbec0a
Added conformance for ExpressibleBy protocols to Optional 2019-06-05 09:59:35 -05:00
Caleb Kleveter 8c9b1a0c49
Created Failable initializer that takes in the Validations type to use 2019-06-05 09:58:13 -05:00
Caleb Kleveter 0cdc51dedc
Fixed optional checking in Failable.value property setter 2019-06-05 09:55:26 -05:00
Caleb Kleveter 400d047e6b
Added .swiftpm/ directory to .gitignore 2019-06-05 07:48:25 -05:00
Caleb Kleveter 359f0e0bdd
Created Failable.get() to extract the internal value for the given instance 2019-06-05 07:47:35 -05:00
Caleb Kleveter 3035415a02
Removed throwing from the <~ operator 2019-06-04 12:50:10 -05:00
Caleb Kleveter 92e0de96ee
Fixed typo in Failable doc comment 2019-06-04 12:25:57 -05:00
Caleb Kleveter 2b30c5ddd8
Check if T is optional when setting Failable.value to 'nil' 2019-06-04 12:17:43 -05:00
Caleb Kleveter f99f5e8c21
Created NonFailable typealias 2019-06-04 12:15:34 -05:00
Caleb Kleveter 88a36b95e4
Created custom operators for Failable types with different validations 2019-06-04 09:45:28 -05:00
Caleb Kleveter ae7896329c
Rebuilt Failable to store errors that occur when validations fail
This allows us to properly conform to a lot more protocols then before, because we never have to throw any errors
2019-05-23 16:48:13 -05:00
Caleb Kleveter 1285049083
Created ErrorJoin struct 2019-05-23 10:20:17 -05:00
Caleb Kleveter cfd74b73a2
Created ValidationError.foundError(_:) static method 2019-05-23 10:19:52 -05:00
Caleb Kleveter 6930d33747
Created EmptyValidation validation type 2019-05-23 10:06:47 -05:00
41 changed files with 1495 additions and 2133 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@
/Packages
/*.xcodeproj
build/
.swiftpm/

View File

@ -1,84 +0,0 @@
// MARK: - Keyed Container
extension KeyedDecodingContainer {
public func decode<T, V>(_ type: Failable<T, V>.Type, forKey key: K) throws -> Failable<T, V> where T: Decodable {
let wrapped = try self.decode(T.self, forKey: key)
return try .init(wrapped)
}
public func decode<T, V>(_ type: Failable<T?, V>.Type, forKey key: K) throws -> Failable<T?, V> where T: Decodable {
let wrapped = try self.decodeIfPresent(T.self, forKey: key)
return try .init(wrapped)
}
}
extension KeyedEncodingContainer {
public mutating func encode<T, V>(_ value: Failable<T, V>, forKey key: K) throws where T: Encodable {
try self.encode(value.value, forKey: key)
}
public mutating func encode<T, V>(_ value: Failable<T?, V>, forKey key: K) throws where T: Encodable {
try self.encodeIfPresent(value.value, forKey: key)
}
}
// MARK: - Unkeyed Container
extension UnkeyedDecodingContainer {
public mutating func decode<T, V>(_ type: Failable<T, V>.Type) throws -> Failable<T, V> where T: Decodable {
let wrapped = try self.decode(T.self)
return try .init(wrapped)
}
public mutating func decode<T, V>(_ type: Failable<T?, V>.Type) throws -> Failable<T?, V> where T: Decodable {
let wrapped = try self.decodeIfPresent(T.self)
return try .init(wrapped)
}
}
extension UnkeyedEncodingContainer {
public mutating func encode<T, V>(_ value: Failable<T, V>) throws where T: Encodable {
try self.encode(value.value)
}
public mutating func encode<T, V>(_ value: Failable<T?, V>) throws where T: Encodable {
if value.value == nil {
try self.encodeNil()
} else {
try self.encode(value.value)
}
}
}
// MARK: Single Value Container
extension SingleValueDecodingContainer {
public func decode<T, V>(_ type: Failable<T, V>.Type) throws -> Failable<T, V> where T: Decodable {
let wrapped = try self.decode(T.self)
return try .init(wrapped)
}
public func decode<T, V>(_ type: Failable<T?, V>.Type) throws -> Failable<T?, V> where T: Decodable {
if self.decodeNil() {
return try .init(nil)
} else {
let wrapped = try self.decode(T.self)
return try .init(wrapped)
}
}
}
extension SingleValueEncodingContainer {
public mutating func encode<T, V>(_ value: Failable<T, V>) throws where T: Encodable {
try self.encode(value.value)
}
public mutating func encode<T, V>(_ value: Failable<T?, V>) throws where T: Encodable {
if value.value == nil {
try self.encodeNil()
} else {
try self.encode(value.value)
}
}
}

View File

@ -16,4 +16,45 @@ public struct ValidationError: Codable, Error {
self.identifier = identifier
self.reason = reason
}
/// Creates a `ValidationError.operationFailed` error.
///
/// This error is used when an operation is called on a `Failable` instance, but the given instance
/// holds an error instead of a valid value.
///
/// - Parameter error: The error held by the `Failable` instance.
/// - Returns: A `ValidationError` instance with `operationFailed` as the identifier.
static func foundError(_ error: Error) -> ValidationError {
return ValidationError(
identifier: "operationFailed",
reason: "Found error instead of expected value.\nError: \(error.localizedDescription)"
)
}
}
/// A combination of two errors that have occured.
public struct ErrorJoin: Error, CustomStringConvertible {
/// One the of the errors that is joined.
public let left: Error
/// One the of the errors that is joined.
public let right: Error
/// Creates a new `ErrorJoin` instance from two other errors.
///
/// - Parameters:
/// - left: One the of the errors that is joined.
/// - right: One the of the errors that is joined.
public init(_ left: Error, _ right: Error) {
self.left = left
self.right = right
}
/// See `CustomStringConvertible.description`.
///
/// - Returns: A string formatted as `(left.description|right.description)`.
public var description: String {
return "(\(self.left.localizedDescription)|\(self.right.localizedDescription))"
}
}

View File

@ -1,7 +1,6 @@
extension Failable where T == Bool {
/// See [`Bool.toggle()`](https://developer.apple.com/documentation/swift/bool/2994863-toggle).
public mutating func toggle()throws {
try self <~ !self.value
public mutating func toggle() {
self.value?.toggle()
}
}

View File

@ -0,0 +1,25 @@
extension Failable: Equatable where T: Equatable {
/// See [`Equatable.==(_:_:)`](https://developer.apple.com/documentation/swift/equatable/1539854).
public static func == (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
switch (lhs.stored, rhs.stored) {
case let (.success(left), .success(right)): return left == right
case let (.failure(left), .failure(right)): return left.localizedDescription == right.localizedDescription
default: return false
}
}
}
extension Failable: Comparable where T: Comparable {
/// See [`Comparable.<(_:_:)`](https://developer.apple.com/documentation/swift/comparable/1538311).
public static func < (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return Failable<Bool, EmptyValidation<Bool>>(Failable.map(lhs, rhs) { left, right in left < right }).value ?? false
}
}
extension Failable: Hashable where T: Hashable {
/// See [`Hashable.hash(into:)`](https://developer.apple.com/documentation/swift/hashable/2995575-hash).
public func hash(into hasher: inout Hasher) {
hasher.combine(String(describing: Validations.self))
hasher.combine(self.value)
}
}

View File

@ -1,80 +1,64 @@
extension Failable: ExpressibleByIntegerLiteral where T: ExpressibleByIntegerLiteral {
/// See [`ExpressibleByIntegerLiteral.IntegerLiteralType`](https://developer.apple.com/documentation/swift/expressiblebyintegerliteral/2295254-integerliteraltype).
public typealias IntegerLiteralType = T.IntegerLiteralType
/// See [`ExpressibleByIntegerLiteral.init(integerLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyintegerliteral/2298913-init).
public init(integerLiteral value: T.IntegerLiteralType) {
let t = T.init(integerLiteral: value)
try! self.init(t)
self = Failable(T(integerLiteral: value))
}
}
extension Failable: ExpressibleByFloatLiteral where T: ExpressibleByFloatLiteral {
/// See [`ExpressibleByFloatLiteral.FloatLiteralType`](https://developer.apple.com/documentation/swift/expressiblebyfloatliteral/2296813-floatliteraltype).
public typealias FloatLiteralType = T.FloatLiteralType
/// See [`ExpressibleByFloatLiteral.init(floatLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyfloatliteral/2294405-init).
public init(floatLiteral value: T.FloatLiteralType) {
let t = T.init(floatLiteral: value)
try! self.init(t)
self = Failable(T(floatLiteral: value))
}
}
extension Failable: ExpressibleByBooleanLiteral where T: ExpressibleByBooleanLiteral {
/// See [`ExpressibleByBooleanLiteral.BooleanLiteralType`](https://developer.apple.com/documentation/swift/expressiblebybooleanliteral/2296130-booleanliteraltype).
public typealias BooleanLiteralType = T.BooleanLiteralType
/// See [`ExpressibleByBooleanLiteral.init(booleanLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebybooleanliteral/2296011-init).
public init(booleanLiteral value: T.BooleanLiteralType) {
let t = T.init(booleanLiteral: value)
try! self.init(t)
self = Failable(T(booleanLiteral: value))
}
}
extension Failable: ExpressibleByNilLiteral where T: ExpressibleByNilLiteral {
/// See [`ExpressibleByNilLiteral.init(nilLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebynilliteral).
public init(nilLiteral: ()) {
let t = T.init(nilLiteral: ())
try! self.init(t)
self = Failable(T(nilLiteral: ()))
}
}
extension Failable: ExpressibleByStringLiteral where T: ExpressibleByStringLiteral {
/// See [`ExpressibleByStringLiteral.StringLiteralType`](https://developer.apple.com/documentation/swift/expressiblebystringliteral/2295780-stringliteraltype).
public typealias StringLiteralType = T.StringLiteralType
/// See [`ExpressibleByStringLiteral.init(stringLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebystringliteral/2294174-init)
public init(stringLiteral value: T.StringLiteralType) {
let t = T.init(stringLiteral: value)
try! self.init(t)
self = Failable(T(stringLiteral: value))
}
}
extension Failable: ExpressibleByExtendedGraphemeClusterLiteral where T: ExpressibleByExtendedGraphemeClusterLiteral {
/// See [`ExpressibleByExtendedGraphemeClusterLiteral.ExtendedGraphemeClusterLiteralType`](https://developer.apple.com/documentation/swift/expressiblebyextendedgraphemeclusterliteral/2297729-extendedgraphemeclusterliteralty).
public typealias ExtendedGraphemeClusterLiteralType = T.ExtendedGraphemeClusterLiteralType
/// See [`ExpressibleByExtendedGraphemeClusterLiteral.init(extendedGraphemeClusterLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyextendedgraphemeclusterliteral/2294280-init).
public init(extendedGraphemeClusterLiteral value: T.ExtendedGraphemeClusterLiteralType) {
let t = T.init(extendedGraphemeClusterLiteral: value)
try! self.init(t)
self = Failable(T(extendedGraphemeClusterLiteral: value))
}
}
extension Failable: ExpressibleByUnicodeScalarLiteral where T: ExpressibleByUnicodeScalarLiteral {
/// See [`ExpressibleByUnicodeScalarLiteral.UnicodeScalarLiteralType`](https://developer.apple.com/documentation/swift/expressiblebyunicodescalarliteral/2297763-unicodescalarliteraltype).
public typealias UnicodeScalarLiteralType = T.UnicodeScalarLiteralType
/// See [`ExpressibleByUnicodeScalarLiteral.init(unicodeScalarLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyunicodescalarliteral/2296043-init).
public init(unicodeScalarLiteral value: T.UnicodeScalarLiteralType) {
let t = T.init(unicodeScalarLiteral: value)
try! self.init(t)
self = Failable(T(unicodeScalarLiteral: value))
}
}
extension Failable: ExpressibleByArrayLiteral where T: ExpressibleByArrayLiteral {
/// See [`ExpressibleByArrayLiteral.init(arrayLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyarrayliteral/2908652-init).
public init(arrayLiteral elements: T.ArrayLiteralElement...) {
let initializer = unsafeBitCast(T.init(arrayLiteral:), to: (([T.ArrayLiteralElement]) -> T).self)
self = Failable(initializer(elements))
}
}
extension Failable: ExpressibleByDictionaryLiteral where T: ExpressibleByDictionaryLiteral {
/// See [`ExpressibleByDictionaryLiteral.init(dictionaryLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebydictionaryliteral/2295781-init).
public init(dictionaryLiteral elements: (T.Key, T.Value)...) {
let initializer = unsafeBitCast(T.init(dictionaryLiteral:), to: (([(T.Key, T.Value)]) -> T).self)
self = Failable(initializer(elements))
}
}

View File

@ -0,0 +1,25 @@
extension Failable: RawRepresentable where T: RawRepresentable {
/// See [`RawRepresentable.RawValue`](https://developer.apple.com/documentation/swift/rawrepresentable/1540809-rawvalue).
public typealias RawValue = Result<T.RawValue, Error>
/// See [`RawRepresentable.init(rawValue:)`](https://developer.apple.com/documentation/swift/rawrepresentable/1538354-inithttps://developer.apple.com/documentation/swift/rawrepresentable/1538354-init)
public init?(rawValue: RawValue) {
guard case let .success(raw) = rawValue, let value = T(rawValue: raw) else { return nil }
self = Failable(value)
}
/// See [`RawRepresentable.rawValue`](https://developer.apple.com/documentation/swift/rawrepresentable/1540698-rawvalue).
public var rawValue: Result<T.RawValue, Error> {
return self[keyPath: \.rawValue]
}
}
extension Failable: CaseIterable where T: CaseIterable {
/// See [`CaseIterable.AllCases`](https://developer.apple.com/documentation/swift/caseiterable/2994868-allcases).
public typealias AllCases = Array<Failable<T, Validations>>
/// See [`CaseIterable.allCases`](https://developer.apple.com/documentation/swift/caseiterable/2994869-allcases)
public static var allCases: AllCases {
return T.allCases.map(Failable.init)
}
}

View File

@ -1,28 +1,22 @@
extension Failable: CustomStringConvertible where T: CustomStringConvertible {
/// See [`CustomStringConvertible.description`](https://developer.apple.com/documentation/swift/customstringconvertible/1539130-description).
public var description: String {
return "Failable(" + self.value.description + ")"
}
}
extension Failable: LosslessStringConvertible where T: LosslessStringConvertible {
/// See [`LosslessStringConvertible.init(_:)`](https://developer.apple.com/documentation/swift/losslessstringconvertible/2429639-init).
///
/// If the value passed into the `Failable` initializer throws an error, the initializer with return `nil`.
public init?(_ description: String) {
guard let value = T(description) else { return nil }
do {
try self.init(value)
} catch {
return nil
switch self.stored {
case let .success(value): return "Failable(" + value.description + ")"
case let .failure(error): return "Failable(error: " + error.localizedDescription + ")"
}
}
}
extension Failable: LosslessStringConvertible where T: LosslessStringConvertible {
/// See [`LosslessStringConvertible.init(_:)`](https://developer.apple.com/documentation/swift/losslessstringconvertible/2429639-init).
public init?(_ description: String) {
guard let value = T(description) else { return nil }
self.init(value)
}
}
extension Failable: CustomDebugStringConvertible where T: CustomDebugStringConvertible {
/// See [`CustomDebugStringConvertible.debugDescription`](https://developer.apple.com/documentation/swift/customdebugstringconvertible/1540125-debugdescription).
public var debugDescription: String {
return "Failable(value: " + self.value.debugDescription + ", validations: " + String(describing: Validations.self) + ")"

View File

@ -0,0 +1,177 @@
// MARK: - Keyed Container
extension KeyedDecodingContainer {
/// Decodes a `Failable` instance with the given stored type for the given key.
///
/// - Parameters:
/// - type: The type of `Failable` instance to decode.
/// - key: The key that the decoded value is associated with.
///
/// - Returns: A value of the requested type, if present for the given key and convertible to the requested type.
public func decode<T, V>(_ type: Failable<T, V>.Type, forKey key: K) throws -> Failable<T, V> where T: Decodable {
let wrapped = try self.decode(T.self, forKey: key)
return try Failable(wrapped).verified()
}
/// Decodes a `Failable` instance with the given stored type for the given key if it exists.
///
/// - Parameters:
/// - type: The type of `Failable` instance to decode.
/// - key: The key that the decoded value is associated with.
///
/// - Returns: A value of the requested type, if present for the given key and convertible to the requested type.
public func decode<T, V>(_ type: Failable<T?, V>.Type, forKey key: K) throws -> Failable<T?, V> where T: Decodable {
let wrapped = try self.decodeIfPresent(T.self, forKey: key)
return try Failable(wrapped).verified()
}
}
extension KeyedEncodingContainer {
func value<T, V>(from failable: Failable<T, V>, for key: K) throws -> T where T: Encodable {
guard let encodable = failable.value else {
throw EncodingError.invalidValue(failable, .init(
codingPath: self.codingPath + [key],
debugDescription: "Cannot encode error as value of type `\(T.self)`",
underlyingError: failable.error
))
}
return encodable
}
/// Encodes the given `Failable` value for the given key.
///
/// - Parameters:
/// - value: The value to encode.
/// - key: The key to associate the value with.
public mutating func encode<T, V>(_ value: Failable<T, V>, forKey key: K) throws where T: Encodable {
try self.encode(self.value(from: value, for: key), forKey: key)
}
/// Encodes the given `Failable` value for the given key if it exists.
///
/// - Parameters:
/// - value: The value to encode.
/// - key: The key to associate the value with.
public mutating func encode<T, V>(_ value: Failable<T?, V>, forKey key: K) throws where T: Encodable {
try self.encodeIfPresent(self.value(from: value, for: key), forKey: key)
}
}
// MARK: - Unkeyed Container
extension UnkeyedDecodingContainer {
/// Decodes a value of the given type.
///
/// - Parameter type: The type of `Failable` instance to decode.
/// - Returns: A value of the requested type, if present for the given key and convertible to the requested type.
public mutating func decode<T, V>(_ type: Failable<T, V>.Type) throws -> Failable<T, V> where T: Decodable {
let wrapped = try self.decode(T.self)
return try Failable(wrapped).verified()
}
/// Decodes a value of the given type.
///
/// - Parameter type: The type of `Failable` instance to decode.
/// - Returns: A value of the requested type, if present for the given key and convertible to the requested type.
public mutating func decode<T, V>(_ type: Failable<T?, V>.Type) throws -> Failable<T?, V> where T: Decodable {
let wrapped = try self.decodeIfPresent(T.self)
return try Failable(wrapped).verified()
}
}
extension UnkeyedEncodingContainer {
func value<T, V>(from failable: Failable<T, V>) throws -> T where T: Encodable {
guard let encodable = failable.value else {
throw EncodingError.invalidValue(failable, .init(
codingPath: self.codingPath,
debugDescription: "Cannot encode error as value of type `\(T.self)`",
underlyingError: failable.error
))
}
return encodable
}
/// Encodes the given `Failable` value.
///
/// - Parameter value: The value to encode.
public mutating func encode<T, V>(_ value: Failable<T, V>) throws where T: Encodable {
try self.encode(self.value(from: value))
}
/// Encodes the given `Failable` value if it exists.
///
/// If the value stored by the `Failable` instance is `nil`, then `.encodeNil()` is called instead.
///
/// - Parameter value: The value to encode.
public mutating func encode<T, V>(_ value: Failable<T?, V>) throws where T: Encodable {
if let encodable = try self.value(from: value) {
try self.encode(encodable)
} else {
try self.encodeNil()
}
}
}
// MARK: Single Value Container
extension SingleValueDecodingContainer {
/// Decodes a single `Failable` value of the given type.
///
/// - Parameter type: The type of `Failable` instance to decode.
/// - Returns: A value of the requested type.
public func decode<T, V>(_ type: Failable<T, V>.Type) throws -> Failable<T, V> where T: Decodable {
let wrapped = try self.decode(T.self)
return try Failable(wrapped).verified()
}
/// Decodes a single `Failable` value of the given type.
///
/// - Parameter type: The type of `Failable` instance to decode.
/// - Returns: A value of the requested type.
public func decode<T, V>(_ type: Failable<T?, V>.Type) throws -> Failable<T?, V> where T: Decodable {
if self.decodeNil() {
return try Failable(nil).verified()
} else {
let wrapped = try self.decode(T.self)
return try Failable(wrapped).verified()
}
}
}
extension SingleValueEncodingContainer {
func value<T, V>(from failable: Failable<T, V>) throws -> T where T: Encodable {
guard let encodable = failable.value else {
throw EncodingError.invalidValue(failable, .init(
codingPath: self.codingPath,
debugDescription: "Cannot encode error as value of type `\(T.self)`",
underlyingError: failable.error
))
}
return encodable
}
/// Encodes a single `Failable` value.
///
/// - Parameter value: The value to encode.
public mutating func encode<T, V>(_ value: Failable<T, V>) throws where T: Encodable {
try self.encode(self.value(from: value))
}
/// Encodes a single `Failable` value if it exists.
///
/// If the value stored by the `Failable` instance is `nil`, then `.encodeNil()` is called instead.
///
/// - Parameter value: The value to encode.
public mutating func encode<T, V>(_ value: Failable<T?, V>) throws where T: Encodable {
if let encodable = try self.value(from: value) {
try self.encode(encodable)
} else {
try self.encodeNil()
}
}
}

View File

@ -0,0 +1,29 @@
extension Failable: Encodable where T: Encodable {
/// See [`Encodable.encode(to:)`](https://developer.apple.com/documentation/swift/encodable/2893603-encode)
public func encode(to encoder: Encoder)throws {
var container = encoder.singleValueContainer()
switch self.stored {
case let .success(value):
try container.encode(value)
case let .failure(error):
throw EncodingError.invalidValue(self, .init(
codingPath: encoder.codingPath,
debugDescription: "Cannot encode error as value of type `\(T.self)`",
underlyingError: error
))
}
}
}
extension Failable: Decodable where T: Decodable {
/// See [`Decodable.init(from:)`](https://developer.apple.com/documentation/swift/decodable/2894081-init)
public init(from decoder: Decoder)throws {
let container = try decoder.singleValueContainer()
if _isOptional(T.self), container.decodeNil() {
self = try Failable(Void?.none as! T).verified()
} else {
self = try Failable(container.decode(T.self)).verified()
}
}
}

View File

@ -0,0 +1,97 @@
extension Failable: Sequence where T: Sequence {
/// See [`Sequence.Element`](https://developer.apple.com/documentation/swift/sequence/2908099-element).
public typealias Element = Failable<T.Element, EmptyValidation<T.Element>>
/// See [`IteratorProtocol`](https://developer.apple.com/documentation/swift/iteratorprotocol).
///
/// Wraps the stored value's iterator and converts the resulting value to a `Failable` instance.
/// If the `Failable` instance holds an error instead of a value, the `.next()` method always returns `nil`.
public struct Iterator: IteratorProtocol {
/// See [`IteratorProtocol.Element`](https://developer.apple.com/documentation/swift/iteratorprotocol/1641632-element).
public typealias Element = Failable.Element
var internalIterator: AnyIterator<T.Element>?
init<I>(iterator: I? = nil) where I: IteratorProtocol, I.Element == T.Element {
self.internalIterator = iterator.map(AnyIterator<T.Element>.init)
}
/// See [`IteratorProtocol.next()`](https://developer.apple.com/documentation/swift/iteratorprotocol/1641682-next).
public mutating func next() -> Element? {
if self.internalIterator != nil {
return (self.internalIterator?.next()).map(Element.init(_:))
} else {
return nil
}
}
}
/// See
/// [`Sequence.underestimatedCount`](https://developer.apple.com/documentation/swift/sequence/3018375-underestimatedcount).
public var underestimatedCount: Int {
return self.value?.underestimatedCount ?? 0
}
/// See [`Sequence.makeIterator()`](https://developer.apple.com/documentation/swift/sequence/2885155-makeiterator).
public func makeIterator() -> Iterator {
return Iterator(iterator: self.value?.makeIterator())
}
}
extension Failable: Collection where T: Collection {
/// See [`Collection.Index`](https://developer.apple.com/documentation/swift/collection/2943866-index).
public typealias Index = Failable<T.Index, EmptyValidation<T.Index>>
/// See [`Collection.startIndex`](https://developer.apple.com/documentation/swift/collection/2946080-startindex).
public var startIndex: Index {
return self[keyPath: \.startIndex]
}
/// See [`Collection.endIndex`](https://developer.apple.com/documentation/swift/collection/2944204-endindex).
public var endIndex: Failable<T.Index, EmptyValidation<T.Index>> {
return self[keyPath: \.endIndex]
}
/// See [`Collection.subscript(_:)`](https://developer.apple.com/documentation/swift/collection/1641358-subscript).
public subscript (position: Index) -> Element {
get {
return Failable.map(self, position) { collection, index in collection[index] }
}
}
/// See [`Collection.index(after:)`](https://developer.apple.com/documentation/swift/collection/2943746-index).
public func index(after i: Failable<T.Index, EmptyValidation<T.Index>>) -> Failable<T.Index, EmptyValidation<T.Index>> {
return Failable.map(self, i) { collection, index in collection.index(after: index) }
}
}
extension Failable: BidirectionalCollection where T: BidirectionalCollection {
/// See [`BidirectionalCollection.index(before:)`](https://developer.apple.com/documentation/swift/bidirectionalcollection/3017603-formindex).
public func index(before i: Failable<T.Index, EmptyValidation<T.Index>>) -> Failable<T.Index, EmptyValidation<T.Index>> {
return Failable.map(self, i) { collection, index in collection.index(before: index) }
}
}
extension Failable: RandomAccessCollection where T: RandomAccessCollection { }
extension Failable: MutableCollection where T: MutableCollection {
/// See [`MutableCollection.subscript(_:)`](https://developer.apple.com/documentation/swift/mutablecollection/1640969-subscript).
public subscript (position: Index) -> Element {
get {
return Failable.map(self, position) { collection, index in collection[index] }
}
set {
if let value = newValue.value, let index = position.value {
self.value?[index] = value
}
}
}
}
extension Failable: RangeReplaceableCollection where T: RangeReplaceableCollection {
/// See [`RangeReplaceableCollection.init()`](https://developer.apple.com/documentation/swift/rangereplaceablecollection/1641467-init).
public init() {
self = Failable(T())
}
}

View File

@ -1,84 +0,0 @@
extension Failable where T: BinaryFloatingPoint {
// MARK: - Typealiases
/// See [`BinaryFloatingPoint.RawExponent`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1846956-rawexponent).
public typealias RawExponent = T.RawExponent
/// See [`BinaryFloatingPoint.RawSignificand`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1848447-rawsignificand).
public typealias RawSignificand = T.RawSignificand
// MARK: - Initializers
/// See [`BinaryFloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1846451-init).
public init(_ value: Float)throws {
let t = T(value)
try self.init(t)
}
/// See [`BinaryFloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1847139-init).
public init(_ value: Double)throws {
let t = T(value)
try self.init(t)
}
/// See [`BinaryFloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1852769-init).
public init(_ value: Float80)throws {
let t = T(value)
try self.init(t)
}
/// See [`BinaryFloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/3017610-init).
public init<Source>(_ value: Source)throws where Source : BinaryFloatingPoint {
let t = T(value)
try self.init(t)
}
/// See [`BinaryFloatingPoint.init(exactly:)`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/3017611-init).
public init?<Source>(exactly value: Source)throws where Source : BinaryFloatingPoint {
guard let t = T(exactly: value) else { return nil }
try? self.init(t)
}
/// See [`BinaryFloatingPoint.init(sign:exponentBitPattern:significandBitPattern:)`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1849503-init).
public init(sign: FloatingPointSign, exponentBitPattern: RawExponent, significandBitPattern: RawSignificand)throws {
let t = T(sign: sign, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern)
try self.init(t)
}
// MARK: - Properties
/// See [`BinaryFloatingPoint.binade`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1848292-binade).
///
/// - Warning: This property has no failing options, so your program will crash if it produces a value that does not pass validation.
public var binade: Failable<T, Validations> {
return try! Failable(self.value.binade)
}
/// See [`BinaryFloatingPoint.exponentBitPattern`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1846505-exponentbitpattern).
public var exponentBitPattern: RawExponent {
return self.value.exponentBitPattern
}
/// See [`BinaryFloatingPoint.significandBitPattern`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1845838-significandbitpattern).
public var significandBitPattern: RawSignificand {
return self.value.significandBitPattern
}
/// See [`BinaryFloatingPoint.significandWidth`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1847322-significandwidth).
public var significandWidth: Int {
return self.value.significandWidth
}
/// See [`BinaryFloatingPoint.exponentBitCount`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1847221-exponentbitcount).
public static var exponentBitCount: Int {
return T.exponentBitCount
}
/// See [`BinaryFloatingPoint.significandBitCount`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1846714-significandbitcount).
public static var significandBitCount: Int {
return T.significandBitCount
}
}

View File

@ -1,367 +0,0 @@
extension Failable where T: BinaryInteger {
/// See [`BinaryInteger.Words`](https://developer.apple.com/documentation/swift/binaryinteger/2894610-words).
public typealias Words = T.Words
/// See [`BinaryInteger.init()`](https://developer.apple.com/documentation/swift/binaryinteger/2885991-init).
public init()throws {
let t = T()
try self.init(t)
}
/// See [`BinaryInteger.init(_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884166-init).
public init<B>(_ source: B)throws where B : BinaryFloatingPoint {
let t = T(source)
try self.init(t)
}
/// See [`BinaryInteger.init(_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885704-init).
public init<B>(_ source: B)throws where B : BinaryInteger {
let t = T(source)
try self.init(t)
}
/// See [`BinaryInteger.init(clamping:)`](https://developer.apple.com/documentation/swift/binaryinteger/2886143-init).
public init<B>(clamping source: B)throws where B : BinaryInteger {
let t = T(clamping: source)
try self.init(t)
}
/// See [`BinaryInteger.init(exactly:)`](https://developer.apple.com/documentation/swift/binaryinteger/2925955-init).
///
/// If an error is thrown by the `Failable` initializer, then this init will return `nil`.
public init?<B>(exactly source: B) where B : BinaryFloatingPoint {
guard let t = T(exactly: source) else { return nil }
try? self.init(t)
}
/// See [`BinaryInteger.init(truncatingIfNeeded:)`](https://developer.apple.com/documentation/swift/binaryinteger/2925529-init).
public init<T>(truncatingIfNeeded source: T)throws where T : BinaryInteger {
let t = T(truncatingIfNeeded: source)
try self.init(t)
}
/// See [`BinaryInteger.bidWidth`](https://developer.apple.com/documentation/swift/binaryinteger/2886690-bitwidth).
public var bidWidth: Int {
return self.value.bitWidth
}
/// See [`BinaryInteger.trailingZeroBitCount`](https://developer.apple.com/documentation/swift/binaryinteger/2886715-trailingzerobitcount).
public var trailingZeroBitCount: Int {
return self.value.trailingZeroBitCount
}
/// See [`BinaryInteger.words`](https://developer.apple.com/documentation/swift/binaryinteger/2892492-words).
public var words: Words {
return self.value.words
}
/// See [`BinaryInteger.isSigned`](https://developer.apple.com/documentation/swift/binaryinteger/2886485-issigned).
public static var isSigned: Bool {
return T.isSigned
}
/// See [`BinaryInteger.quotientAndRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017639-quotientandremainder).
public func quotientAndRemainder(dividingBy rhs: Failable<T, Validations>)throws
-> (quotient: Failable<T, Validations>, remainder: Failable<T, Validations>)
{
let qar = self.value.quotientAndRemainder(dividingBy: rhs.value)
return try (Failable(qar.quotient), Failable(qar.remainder))
}
/// See [`BinaryInteger.signum()`](https://developer.apple.com/documentation/swift/binaryinteger/3017643-signum).
public func signum()throws -> Failable<T, Validations> {
return try Failable(self.value.signum())
}
/// See [`BinaryInteger.!=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885339).
public static func != <Other>(lhs: Failable<T, Validations>, rhs: Other) -> Bool where Other : BinaryInteger {
return lhs.value != rhs
}
/// See [`BinaryInteger.!=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885737).
public static func != (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value != rhs.value
}
/// See [`BinaryInteger.%(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885003).
public static func % (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value % rhs.value)
}
/// See [`BinaryInteger.%=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2886158).
public static func %= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs % rhs
}
/// See [`BinaryInteger.&(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017613).
public static func & (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value & rhs.value)
}
/// See [`BinaryInteger.&=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885976).
public static func &= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs & rhs
}
/// See [`BinaryInteger.*(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884580).
public static func * (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value * rhs.value)
}
/// See [`BinaryInteger.*=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884627).
public static func *= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs * rhs
}
/// See [`BinaryInteger.+(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885923).
public static func + (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value + rhs.value)
}
/// See [`BinaryInteger.+=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2886064).
public static func += (lhs: inout Failable<T, Validations> , rhs: Failable<T, Validations> )throws {
try lhs = lhs + rhs
}
/// See [`BinaryInteger.-(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884248).
public static func - (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value - rhs.value)
}
/// See [`BinaryInteger.-=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884261).
public static func -= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs - rhs
}
/// See [`BinaryInteger./(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885552).
public static func / (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value / rhs.value)
}
/// See [`BinaryInteger./=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885191).
public static func /= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs / rhs
}
/// See [`BinaryInteger.<(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885984).
public static func < <Other>(lhs: Failable<T, Validations>, rhs: Other) -> Bool where Other : BinaryInteger {
return lhs.value < rhs
}
/// See [`BinaryInteger.<<(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017617).
public static func << <RHS>(lhs: Failable<T, Validations>, rhs: RHS)throws -> Failable<T, Validations> where RHS : BinaryInteger {
return try Failable(lhs.value << rhs)
}
/// See [`BinaryInteger.<<=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2926303).
public static func <<= <RHS>(lhs: inout Failable<T, Validations>, rhs: RHS)throws where RHS : BinaryInteger {
try lhs = lhs << rhs
}
/// See [`BinaryInteger.<=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884735).
public static func <= (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value <= rhs.value
}
/// See [`BinaryInteger.<=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2886797).
public static func <= <Other>(lhs: Failable<T, Validations>, rhs: Other) -> Bool where Other : BinaryInteger {
return lhs.value <= rhs
}
/// See [`BinaryInteger.==(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2886030).
public static func == <Other>(lhs: Failable<T, Validations>, rhs: Other) -> Bool where Other : BinaryInteger {
return lhs.value == rhs
}
/// See [`BinaryInteger.>(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884492).
public static func > <Other>(lhs: Failable<T, Validations>, rhs: Other) -> Bool where Other : BinaryInteger {
return lhs.value > rhs
}
/// See [`BinaryInteger.>(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2886190).
public static func > (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value > rhs.value
}
/// See [`BinaryInteger.>=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2883970).
public static func >= (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value == rhs.value
}
/// See [`BinaryInteger.>=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885916).
public static func >= <Other>(lhs: Failable<T, Validations>, rhs: Other) -> Bool where Other : BinaryInteger {
return lhs.value >= rhs
}
/// See [`BinaryInteger.>>(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017625).
public static func >> <RHS>(lhs: Failable<T, Validations>, rhs: RHS)throws -> Failable<T, Validations> where RHS: BinaryInteger {
return try Failable(lhs.value >> rhs)
}
/// See [`BinaryInteger.>>=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2926011).
public static func >>= <RHS>(lhs: inout Failable<T, Validations>, rhs: RHS)throws where RHS : BinaryInteger {
try lhs = lhs >> rhs
}
/// See [`BinaryInteger.^(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017635).
public static func ^ (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value ^ rhs.value)
}
/// See [`BinaryInteger.^=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885182).
public static func ^= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs ^ rhs
}
/// See [`BinaryInteger.|(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017645).
public static func | (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value | rhs.value)
}
/// See [`BinaryInteger.|=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884669).
public static func |= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs | rhs
}
/// See [`BinaryInteger.~(_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2883740).
public prefix static func ~ (x: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(~x.value)
}
}
/// Checks for inequality between two `Failable` values iw the same stored type but different validations.
///
/// - Parameters:
/// - lhs: The left value to check.
/// - rhs: The right value to check.
///
/// - Returns: The boolean value that represents whether the value are non-equal or not.
public func != <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: BinaryInteger {
return lhs.value != rhs.value
}
/// Produces the remainder of dividing a `Failable` value by another, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The dividend in the equation.
/// - rhs: The divisor in the equation.
///
/// - Returns: The remainder of the division problem, with the validations of both `Failalble` types passed in.
public func % <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: BinaryInteger {
return try Failable(lhs.value % rhs.value)
}
/// Produces the result of a bitwise AND operatoion on two `Failable` values, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The left value for the operation.
/// - rhs: The right value for the operation.
///
/// - Returns: The result of the operation, with the validations of both `Failalble` types passed in.
public func & <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: BinaryInteger {
return try Failable(lhs.value & rhs.value)
}
/// Produces the product of two `Failable` values, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The value to multiply.
/// - rhs: The value to multiply the first value by.
///
/// - Returns: The product of the equation, with the validations of both `Failalble` types passed in.
public func * <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: BinaryInteger {
return try Failable(lhs.value * rhs.value)
}
/// Produces the sum of two `Failable` values, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The left value to add.
/// - rhs: The right value to add.
///
/// - Returns: The sum of the two values, with the validations of both `Failalble` types passed in.
public func + <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: BinaryInteger {
return try Failable(lhs.value + rhs.value)
}
/// Produces the difference of two `Failable` values, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The value to subtract from.
/// - rhs: The value to subtract from the left value.
///
/// - Returns: The difference of the two values, with the validations of both `Failalble` types passed in.
public func - <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: BinaryInteger {
return try Failable(lhs.value - rhs.value)
}
/// Produces the quotient of dividing on `Failable` value by another, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The dividend in the equation.
/// - rhs: The divisor in the equation.
///
/// - Returns: The quotient of the division problem, with the validations of both `Failalble` types passed in.
public func / <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: BinaryInteger {
return try Failable(lhs.value / rhs.value)
}
/// Returns a Boolean value indicating whether the value of the first argument is less than
/// or equal to that of the second argument, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The left value to check.
/// - rhs: The right value to check.
///
/// - Returns: The boolean value that represents whether the first value is less than or equal to the second.
public func <= <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: BinaryInteger {
return lhs.value <= rhs.value
}
/// Returns a Boolean value indicating whether the value of the first argument is greater than
/// that of the second argument, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The left value to check.
/// - rhs: The right value to check.
///
/// - Returns: The boolean value that represents whether the first value is greater than the second.
public func > <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: BinaryInteger {
return lhs.value > rhs.value
}
/// Returns a Boolean value indicating whether the value of the first argument is greater than
/// or equal to that of the second argument, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The left value to check.
/// - rhs: The right value to check.
///
/// - Returns: The boolean value that represents whether the first value is greater than or equal to the second.
public func >= <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: BinaryInteger {
return lhs.value == rhs.value
}
/// Returns the result of performing a bitwise XOR operation on the two given values, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The left value in the operation.
/// - rhs: The right value in the operation.
///
/// - Returns: The result of the XOR operation, with the validation types from both values passed in.
public func ^ <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: BinaryInteger {
return try Failable(lhs.value ^ rhs.value)
}
/// Returns the result of performing a bitwise OR operation on the two given values, where the `Validations` types are different.
///
/// - Parameters:
/// - lhs: The left value in the operation.
/// - rhs: The right value in the operation.
///
/// - Returns: The result of the OR operation, with the validation types from both values passed in.
public func | <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: BinaryInteger {
return try Failable(lhs.value | rhs.value)
}

View File

@ -1,28 +0,0 @@
extension Failable: Encodable where T: Encodable {
/// See [`Encodable.encode(to:)`](https://developer.apple.com/documentation/swift/encodable/2893603-encode)
public func encode(to encoder: Encoder)throws {
var container = encoder.singleValueContainer()
try container.encode(self.value)
}
}
extension Failable: Decodable where T: Decodable {
/// See [`Decodable.init(from:)`](https://developer.apple.com/documentation/swift/decodable/2894081-init)
public init(from decoder: Decoder)throws {
let container = try decoder.singleValueContainer()
guard _isOptional(T.self) else {
try self.init(try container.decode(T.self))
return
}
guard container.decodeNil() else {
try self.init(try container.decode(T.self))
return
}
try self.init(Void?.none as! T)
}
}

View File

@ -1,94 +0,0 @@
extension Failable: Collection where T: Collection {
/// See [`Collection.SubSequence`](https://developer.apple.com/documentation/swift/collection/1641276-subsequence)
public typealias SubSequence = T.SubSequence
/// See [`Collection.Index`](https://developer.apple.com/documentation/swift/collection/2943866-index).
public typealias Index = T.Index
/// See [`Collection.startIndex`](https://developer.apple.com/documentation/swift/collection/2946080-startindex).
public var startIndex: T.Index {
return self.value.startIndex
}
/// See [`Collection.endIndex`](https://developer.apple.com/documentation/swift/collection/2944204-endindex).
public var endIndex: T.Index {
return self.value.endIndex
}
/// See [`Collection.[]`](https://developer.apple.com/documentation/swift/collection/1641358-subscript).
public subscript(position: Index) -> Element {
return self.value[position]
}
/// See [`Collection.index(after:)`](https://developer.apple.com/documentation/swift/collection/2943746-index).
public func index(after i: T.Index) -> T.Index {
return self.value.index(after: i)
}
}
extension Failable: BidirectionalCollection where T: BidirectionalCollection {
/// See [`BidirectionalCollection.index(before:)`](https://developer.apple.com/documentation/swift/bidirectionalcollection/1783013-index).
public func index(before i: T.Index) -> T.Index {
return self.value.index(before: i)
}
}
extension Failable: RandomAccessCollection where T: RandomAccessCollection {}
extension Failable where T: MutableCollection {
/// See [`MutableCollection.[]`](https://developer.apple.com/documentation/swift/mutablecollection/1640969-subscript).
///
/// To validate the new array, the instance is copied and mutated, then the validation is run on the mutated instance.
/// If the validation succeeds, the mutated value is assigned to the current instance. If the validation fails, the set silently fails.
public subscript(position: T.Index) -> T.Element {
get {
return self.value[position]
}
set(newValue) {
var copy = self
copy.value[position] = newValue
do {
try self <~ copy.value
} catch {}
}
}
/// See [`MutableCollection.[]`](https://developer.apple.com/documentation/swift/mutablecollection/2965317-subscript).
///
/// To validate the new array, the instance is copied and mutated, then the validation is run on the mutated instance.
/// If the validation succeeds, the mutated value is assigned to the current instance. If the validation fails, the set silently fails.
public subscript(position: Range<T.Index>) -> T.SubSequence {
get {
return self.value[position]
}
set(newValue) {
var copy = self
copy.value[position] = newValue
do {
try self <~ copy.value
} catch {}
}
}
/// See [`MutableCollection.partition(by:)`](https://developer.apple.com/documentation/swift/mutablecollection/3018221-partition).
public mutating func partition(by belongsInSecondPartition: (Element) throws -> Bool)throws -> Index {
var copy = self.value
let index = try copy.partition(by: belongsInSecondPartition)
try self <~ copy
return index
}
/// See [`MutableCollection.swapAt(_:_:)`](https://developer.apple.com/documentation/swift/mutablecollection/3018230-swapat).
public mutating func swapAt(_ i: Index, _ j: Index)throws {
var copy = self.value
copy.swapAt(i, j)
try self <~ copy
}
}

View File

@ -1,112 +0,0 @@
// MARK: - Equatable
extension Failable: Equatable where T: Equatable {
/// See [`Equatable.==(-:_:)`](https://developer.apple.com/documentation/swift/equatable/1539854).
public static func == (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value == rhs.value
}
}
/// Checks for equality of the `value` property from two `Failable` instances where type `T` is the same and comforms to `Equatable`,
/// but the `Validations` are different.
///
/// - Parameters:
/// - lhs: The left `Failable` instance to compare.
/// - rhs: The right `Failable` instance to compare.
public func == <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: Equatable {
return lhs.value == rhs.value
}
/// Checks for equality of the `value` property from one `Failable` instances with another value of type `T`.
///
/// - Parameters:
/// - lhs: The `Failable` instance to compare.
/// - rhs: The `T` value to compare.
public func == <T, V1>(lhs: Failable<T, V1>, rhs: T) -> Bool where T: Equatable {
return lhs.value == rhs
}
/// Checks for inequality of the `value` property from two `Failable` instances where type `T` is the same and comforms to `Equatable`,
/// but the `Validations` are different.
///
/// - Parameters:
/// - lhs: The left `Failable` instance to compare.
/// - rhs: The right `Failable` instance to compare.
public func != <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: Equatable {
return lhs.value != rhs.value
}
/// Checks for inequality of the `value` property from one `Failable` instances with another value of type `T`.
///
/// - Parameters:
/// - lhs: The `Failable` instance to compare.
/// - rhs: The `T` value to compare.
public func != <T, V1>(lhs: Failable<T, V1>, rhs: T) -> Bool where T: Equatable {
return lhs.value != rhs
}
// MARK: - Comparable
extension Failable: Comparable where T: Comparable {
/// See [`Comparable.<(_:_:)`](https://developer.apple.com/documentation/swift/comparable/1538311)
public static func < (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value < rhs.value
}
}
/// See [`Comparable....(_:_:)`](https://developer.apple.com/documentation/swift/comparable/2949800).
public func ... <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws
-> Failable<ClosedRange<T>, ElementValidation<ClosedRange<T>, AppendedValidations<T, V1, V2>>> where T: Comparable
{
return try Failable(lhs.value...rhs.value)
}
/// See [`Comparable...<(_:_:)`](https://developer.apple.com/documentation/swift/comparable/2949700).
public func ..< <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws
-> Failable<Range<T>, ElementValidation<Range<T>, AppendedValidations<T, V1, V2>>> where T: Comparable
{
return try Failable(lhs.value..<rhs.value)
}
/// Checks that the `value` property from one `Failable` instance is great than another, where type `T` is the same and comforms to `Comparable`,
/// but the `Validations` are different.
///
/// - Parameters:
/// - lhs: The left `Failable` instance to compare.
/// - rhs: The right `Failable` instance to compare.
public func > <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: Comparable {
return lhs.value > rhs.value
}
/// Checks that the `value` property from one `Failable` instance is less than another, where type `T` is the same and comforms to `Comparable`,
/// but the `Validations` are different.
///
/// - Parameters:
/// - lhs: The left `Failable` instance to compare.
/// - rhs: The right `Failable` instance to compare.
public func < <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: Comparable {
return lhs.value < rhs.value
}
/// Checks that the `value` property from one `Failable` instance is great than or equal to another,
/// where type `T` is the same and comforms to `Comparable`, but the `Validations` are different.
///
/// - Parameters:
/// - lhs: The left `Failable` instance to compare.
/// - rhs: The right `Failable` instance to compare.
public func >= <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: Comparable {
return lhs.value >= rhs.value
}
/// Checks that the `value` property from one `Failable` instance is less than or equal to another,
/// where type `T` is the same and comforms to `Comparable`, but the `Validations` are different.
///
/// - Parameters:
/// - lhs: The left `Failable` instance to compare.
/// - rhs: The right `Failable` instance to compare.
public func <= <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: Comparable {
return lhs.value <= rhs.value
}

View File

@ -1,290 +0,0 @@
extension Failable where T: FixedWidthInteger {
// MARK: - Initializers
/// See [`FixedWidthInteger.init(_:radix:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2924552-init).
///
/// If an error is thrown by the `Failable` initializer, this init will return `nil`.
public init?<S>(_ text: S, radix: Int = 10) where S : StringProtocol {
guard let t = T(text, radix: radix) else { return nil }
try? self.init(t)
}
/// See [`FixedWidthInteger.init(bigEndian:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2964311-init).
public init(bigEndian value: Failable<T, Validations>)throws {
let t = T(bigEndian: value.value)
try self.init(t)
}
/// See [`FixedWidthInteger.init(littleEndian:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2964313-init).
public init(littleEndian value: Failable<T, Validations>)throws {
let t = T(littleEndian: value.value)
try self.init(t)
}
/// See [`FixedWidthInteger.init(bigEndian:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2964311-init).
public init<V>(bigEndian value: Failable<T, V>)throws {
let t = T(bigEndian: value.value)
try self.init(t)
}
/// See [`FixedWidthInteger.init(littleEndian:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2964313-init).
public init<V>(littleEndian value: Failable<T, V>)throws {
let t = T(littleEndian: value.value)
try self.init(t)
}
// MARK: - Properties
/// See [`FixedWidthInteger.bigEndian`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2946083-bigendian).
///
/// - Warning: This property has no failing options, so your program will crash if it produces a value that does not pass validation.
public var bigEndian: Failable<T, Validations> {
return try! Failable(self.value.bigEndian)
}
/// A representation of this integer with the byte order swapped.
///
/// - Warning: This property has no failing options, so your program will crash if it produces a value that does not pass validation.
public var byteSwapped: Failable<T, Validations> {
return try! Failable(self.value.byteSwapped)
}
/// See [`FixedWidthInteger.leadingZeroBitCount`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2883995-leadingzerobitcount).
public var leadingZeroBitCount: Int {
return self.value.leadingZeroBitCount
}
/// See [`FixedWidthInteger.littleEndian`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2944924-littleendian).
///
/// - Warning: This property has no failing options, so your program will crash if it produces a value that does not pass validation.
public var littleEndian: Failable<T, Validations> {
return try! Failable(self.value.littleEndian)
}
/// See [`FixedWidthInteger.nonzeroBitCount`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2885911-nonzerobitcount).
public var nonzeroBitCount: Int {
return self.value.nonzeroBitCount
}
// MARK: - Static Properties
/// See [`FixedWidthInteger.bitWidth`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2886552-bitwidth).
public static var bitWidth: Int {
return T.bitWidth
}
/// See [`FixedWidthInteger.max`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2883788-max).
///
/// - Warning: This property has no failing options, so your program will crash if it produces a value that does not pass validation.
public static var max: Failable<T, Validations> {
return try! Failable(T.max)
}
/// See [`FixedWidthInteger.min`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884515-min).
///
/// - Warning: This property has no failing options, so your program will crash if it produces a value that does not pass validation.
public static var min: Failable<T, Validations> {
return try! Failable(T.min)
}
// MARK: - Instance Methods
/// See [`FixedWidthInteger.addingReportingOverflow(_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2885260-addingreportingoverflow).
public func addingReportingOverflow(_ rhs: Failable<T, Validations>)throws -> (partialValue: Failable<T, Validations>, overflow: Bool) {
let aro = self.value.addingReportingOverflow(rhs.value)
return try (Failable(aro.partialValue), aro.overflow)
}
/// See [`FixedWidthInteger.dividedReportingOverflow(_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2885588-dividedreportingoverflow).
public func dividedReportingOverflow(by rhs: Failable<T, Validations>)throws -> (partialValue: Failable<T, Validations>, overflow: Bool) {
let dro = self.value.dividedReportingOverflow(by: rhs.value)
return try (Failable(dro.partialValue), dro.overflow)
}
/// See [`FixedWidthInteger.dividingFullWidth(_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884055-dividingfullwidth).
public func dividingFullWidth(_ dividend: (high: Failable<T, Validations>, low: Failable<T, Validations>.Magnitude))throws
-> (quotient: Failable<T, Validations>, remainder: Failable<T, Validations>)
{
let dfw = self.value.dividingFullWidth((dividend.high.value, dividend.low))
return try (Failable(dfw.quotient), Failable(dfw.remainder))
}
/// See [`FixedWidthInteger.multipliedFullWidth(by:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884581-multipliedfullwidth).
public func multipliedFullWidth(by other: Failable<T, Validations>)throws
-> (high: Failable<T, Validations>, low: Failable<T, Validations>.Magnitude)
{
let mfw = self.value.multipliedFullWidth(by: other.value)
return try (Failable(mfw.high), mfw.low)
}
/// See [`FixedWidthInteger.multipliedReportingOverflow(by:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884864-multipliedreportingoverflow).
public func multipliedReportingOverflow(by rhs: Failable<T, Validations>)throws -> (partialValue: Failable<T, Validations>, overflow: Bool) {
let mro = self.value.multipliedReportingOverflow(by: rhs.value)
return try (Failable(mro.partialValue), mro.overflow)
}
/// See [`FixedWidthInteger.remainderReportingOverflow(dividingBy:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2892758-remainderreportingoverflow).
public func remainderReportingOverflow(dividingBy rhs: Failable<T, Validations>)throws
-> (partialValue: Failable<T, Validations>, overflow: Bool)
{
let rro = self.value.remainderReportingOverflow(dividingBy: rhs.value)
return try (Failable(rro.partialValue), rro.overflow)
}
/// See [`FixedWidthInteger.subtractingReportingOverflow(_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2885098-subtractingreportingoverflow).
public func subtractingReportingOverflow(_ rhs: Failable<T, Validations>)throws -> (partialValue: Failable<T, Validations>, overflow: Bool) {
let sro = self.value.subtractingReportingOverflow(rhs.value)
return try (Failable(sro.partialValue), sro.overflow)
}
// MARK: - Static Methods
/// See [`FixedWidthInteger.random(in:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2995512-random)
public static func random(in range: ClosedRange<Failable<T, Validations>>)throws -> Failable<T, Validations> {
return try Failable(T.random(in: range.lowerBound.value...range.upperBound.value))
}
/// See [`FixedWidthInteger.random(in:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2995514-random)
public static func random(in range: Range<Failable<T, Validations>>)throws -> Failable<T, Validations> {
return try Failable(T.random(in: range.lowerBound.value..<range.upperBound.value))
}
/// See [`FixedWidthInteger.random(in:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/3020576-random)
public static func random<G>(in range: ClosedRange<Failable<T, Validations>>, using generator: inout G)throws
-> Failable<T, Validations> where G : RandomNumberGenerator
{
return try Failable(T.random(in: range.lowerBound.value...range.upperBound.value, using: &generator))
}
/// See [`FixedWidthInteger.random(in:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/3020578-random)
public static func random<G>(in range: Range<Failable<T, Validations>>, using generator: inout G)throws
-> Failable<T, Validations> where G : RandomNumberGenerator
{
return try Failable(T.random(in: range.lowerBound.value..<range.upperBound.value, using: &generator))
}
// MARK: - Operators
/// See [`FixedWidthInteger.&*(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884714).
public static func &* (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value &* rhs.value)
}
/// See [`FixedWidthInteger.&*=(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2995497).
public static func &*= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs &* rhs
}
/// See [`FixedWidthInteger.&+(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884804).
public static func &+ (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value &+ rhs.value)
}
/// See [`FixedWidthInteger.&+=(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2995499).
public static func &+= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs &+ rhs
}
/// See [`FixedWidthInteger.&-(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884345-_).
public static func &- (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value &- rhs.value)
}
/// See [`FixedWidthInteger.&-=(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2995501-_).
public static func &-= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs &- rhs
}
/// See [`FixedWidthInteger.&<<(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2964298).
public static func &<< (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value &<< rhs.value)
}
/// See [`FixedWidthInteger.&<<=(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2925973).
public static func &<<= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs &<< rhs
}
/// See [`FixedWidthInteger.&>>(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2964304).
public static func &>> (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value &>> rhs.value)
}
/// See [`FixedWidthInteger.&>>=(_:_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2924977).
public static func &>>= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs = lhs &>> rhs
}
}
/// Returns the product of the two given `Failable` values, wrapping the result in case of any overflow.
///
/// - Parameters:
/// - lhs: The left value to multiply.
/// - rhs: The right value to mutiply.
///
/// - Returns: The product of the multiplcation equation, with validation types from the values passed in mixed.
public func &* <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws
-> Failable<T, AppendedValidations<T, V1, V2>> where T: FixedWidthInteger
{
return try Failable(lhs.value &* rhs.value)
}
/// Returns the sum of the two given values, wrapping the result in case of any overflow.
///
/// - Parameters:
/// - lhs: The left value to add.
/// - rhs: The right value to add.
///
/// - Returns: The sum of the addition equation, with validation types from the values passed in mixed.
public func &+ <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws
-> Failable<T, AppendedValidations<T, V1, V2>> where T: FixedWidthInteger
{
return try Failable(lhs.value &+ rhs.value)
}
/// Returns the difference of the two given values, wrapping the result in case of any overflow.
///
/// - Parameters:
/// - lhs: The value to subtract from.
/// - rhs: The value to subtract from the left value.
///
/// - Returns: The difference of the subtraction equation, with validation types from the values passed in mixed.
public func &- <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws
-> Failable<T, AppendedValidations<T, V1, V2>> where T: FixedWidthInteger
{
return try Failable(lhs.value &- rhs.value)
}
/// Returns the result of shifting a values binary representation the specified number of digits to the left,
/// masking the shift amount to the types bit width.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The amount to shift the left value by.
///
/// - Returns: The result of the shift operation, with validation types from the values passed in mixed.
public func &<< <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws
-> Failable<T, AppendedValidations<T, V1, V2>> where T: FixedWidthInteger
{
return try Failable(lhs.value &<< rhs.value)
}
/// Returns the result of shifting a values binary representation the specified number of digits to the right,
/// masking the shift amount to the types bit width.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The amount to shift the left value by.
///
/// - Returns: The result of the shift operation, with validation types from the values passed in mixed.
public func &>> <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws
-> Failable<T, AppendedValidations<T, V1, V2>> where T: FixedWidthInteger
{
return try Failable(lhs.value &>> rhs.value)
}

View File

@ -1,563 +0,0 @@
extension Failable where T: FloatingPoint {
// MARK: - Typealiases
/// See [`FloatingPoint.Exponent`](https://developer.apple.com/documentation/swift/floatingpoint/1848224-exponent).
public typealias Exponent = T.Exponent
// MARK: - Initializers
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641558-init).
public init(_ value: Int8)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641150-init).
public init(_ value: Int16)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641192-init).
public init(_ value: Int32)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641208-init).
public init(_ value: Int64)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641277-init).
public init(_ value: UInt8)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641505-init).
public init(_ value: UInt16)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641406-init).
public init(_ value: UInt32)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641403-init).
public init(_ value: UInt64)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641530-init).
public init(_ value: UInt)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641560-init).
public init(_ value: Int)throws {
let t = T(value)
try self.init(t)
}
/// See [`FloatingPoint.init(exactly:)`](https://developer.apple.com/documentation/swift/floatingpoint/2964416-init).
public init?<Source>(exactly value: Source) where Source : BinaryInteger {
guard let t = T(exactly: value) else { return nil }
try? self.init(t)
}
/// See [`FloatingPoint.init(sign:exponent:significand:)`](https://developer.apple.com/documentation/swift/floatingpoint/1845755-init).
public init(sign: FloatingPointSign, exponent: Exponent, significand: Failable<T, Validations>)throws {
let t = T(sign: sign, exponent: exponent, significand: significand.value)
try self.init(t)
}
/// See [`FloatingPoint.init(signOf:magnitudeOf:)`](https://developer.apple.com/documentation/swift/floatingpoint/1849294-init).
public init(signOf: Failable<T, Validations>, magnitudeOf: Failable<T, Validations>)throws {
let t = T(signOf: signOf.value, magnitudeOf: magnitudeOf.value)
try self.init(t)
}
/// See [`FloatingPoint.init(sign:exponent:significand:)`](https://developer.apple.com/documentation/swift/floatingpoint/1845755-init).
public init<V>(sign: FloatingPointSign, exponent: Exponent, significand: Failable<T, V>)throws {
let t = T(sign: sign, exponent: exponent, significand: significand.value)
try self.init(t)
}
/// See [`FloatingPoint.init(signOf:magnitudeOf:)`](https://developer.apple.com/documentation/swift/floatingpoint/1849294-init).
public init<V1, V2>(signOf: Failable<T, V1>, magnitudeOf: Failable<T, V2>)throws {
let t = T(signOf: signOf.value, magnitudeOf: magnitudeOf.value)
try self.init(t)
}
// MARK: - Properties
/// See [`FloatingPoint.exponent`](https://developer.apple.com/documentation/swift/floatingpoint/1846275-exponent).
public var exponent: Exponent {
return self.value.exponent
}
/// See [`FloatingPoint.floatingPointClass`](https://developer.apple.com/documentation/swift/floatingpoint/3017961-floatingpointclass).
public var floatingPointClass: FloatingPointClassification {
return self.value.floatingPointClass
}
/// See [`FloatingPoint.isCanonical`](https://developer.apple.com/documentation/swift/floatingpoint/1847929-iscanonical).
public var isCanonical: Bool {
return self.value.isCanonical
}
/// See [`FloatingPoint.isFinite`](https://developer.apple.com/documentation/swift/floatingpoint/1641190-isfinite).
public var isFinite: Bool {
return self.value.isFinite
}
/// See [`FloatingPoint.isInfinite`](https://developer.apple.com/documentation/swift/floatingpoint/1641669-isinfinite).
public var isInfinite: Bool {
return self.value.isInfinite
}
/// See [`FloatingPoint.isNaN`](https://developer.apple.com/documentation/swift/floatingpoint/1641763-isnan).
public var isNaN: Bool {
return self.value.isNaN
}
/// See [`FloatingPoint.isNormal`](https://developer.apple.com/documentation/swift/floatingpoint/1641394-isnormal).
public var isNormal: Bool {
return self.value.isNormal
}
/// See [`FloatingPoint.isSignalingNaN`](https://developer.apple.com/documentation/swift/floatingpoint/1847971-issignalingnan).
public var isSignalingNaN: Bool {
return self.value.isSignalingNaN
}
/// See [`FloatingPoint.isSubnormal`](https://developer.apple.com/documentation/swift/floatingpoint/1641181-issubnormal).
public var isSubnormal: Bool {
return self.value.isSubnormal
}
/// See [`FloatingPoint.isZero`](https://developer.apple.com/documentation/swift/floatingpoint/1641514-iszero).
public var isZero: Bool {
return self.value.isZero
}
/// See [`FloatingPoint.nextDown`](https://developer.apple.com/documentation/swift/floatingpoint/3017979-nextdown).
public var nextDown: Failable<T, Validations> {
return try! Failable(self.value.nextDown)
}
/// See [`FloatingPoint.nextUp`](https://developer.apple.com/documentation/swift/floatingpoint/1848104-nextup).
public var nextUp: Failable<T, Validations> {
return try! Failable(self.value.nextUp)
}
/// See [`FloatingPoint.sign`](https://developer.apple.com/documentation/swift/floatingpoint/1847735-sign).
public var sign: FloatingPointSign {
return self.value.sign
}
/// See [`FloatingPoint.significand`](https://developer.apple.com/documentation/swift/floatingpoint/1847298-significand).
public var significand: Failable<T, Validations> {
return try! Failable(self.value.significand)
}
/// See [`FloatingPoint.ulp`](https://developer.apple.com/documentation/swift/floatingpoint/1847492-ulp).
public var ulp: Failable<T, Validations> {
return try! Failable(self.value.ulp)
}
// MARK: - Static Properties
/// See [`FloatingPoint.greatestFiniteMagnitude`](https://developer.apple.com/documentation/swift/floatingpoint/1849534-greatestfinitemagnitude).
public static var greatestFiniteMagnitude: Failable<T, Validations> {
return try! Failable(T.greatestFiniteMagnitude)
}
/// See [`FloatingPoint.infinity`](https://developer.apple.com/documentation/swift/floatingpoint/1641304-infinity).
public static var infinity: Failable<T, Validations> {
return try! Failable(T.infinity)
}
/// See [`FloatingPoint.leastNonzeroMagnitude`](https://developer.apple.com/documentation/swift/floatingpoint/1848591-leastnonzeromagnitude).
public static var leastNonzeroMagnitude: Failable<T, Validations> {
return try! Failable(T.leastNonzeroMagnitude)
}
/// See [`FloatingPoint.leastNormalMagnitude`](https://developer.apple.com/documentation/swift/floatingpoint/1849504-leastnormalmagnitude).
public static var leastNormalMagnitude: Failable<T, Validations> {
return try! Failable(T.leastNormalMagnitude)
}
/// See [`FloatingPoint.nan`](https://developer.apple.com/documentation/swift/floatingpoint/1641652-nan).
public static var nan: Failable<T, Validations> {
return try! Failable(T.nan)
}
/// See [`FloatingPoint.pi`](https://developer.apple.com/documentation/swift/floatingpoint/1845454-pi).
public static var pi: Failable<T, Validations> {
return try! Failable(T.pi)
}
/// See [`FloatingPoint.radix`](https://developer.apple.com/documentation/swift/floatingpoint/1846156-radix).
public static var radix: Failable<T, Validations> {
return try! Failable(T.radix)
}
/// See [`FloatingPoint.signalingNaN`](https://developer.apple.com/documentation/swift/floatingpoint/1845864-signalingnan).
public static var signalingNaN: Failable<T, Validations> {
return try! Failable(T.signalingNaN)
}
/// See [`FloatingPoint.ulpOfOne`](https://developer.apple.com/documentation/swift/floatingpoint/3017999-ulpofone).
public static var ulpOfOne: Failable<T, Validations> {
return try! Failable(T.ulpOfOne)
}
// MARK: - Instance Methods
/// See [`FloatingPoint.addProduct(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2295205-addproduct).
public mutating func addProduct(_ lhs: Failable<T, Validations>, _ rhs: Failable<T, Validations>) {
self.value.addProduct(lhs.value, rhs.value)
}
/// See [`FloatingPoint.addingProduct(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017959-addingproduct).
public func addingProduct(_ lhs: Failable<T, Validations>, _ rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(self.value.addingProduct(lhs.value, rhs.value))
}
/// See [`FloatingPoint.formRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/2299459-formremainder).
public mutating func formRemainder(dividingBy other: Failable<T, Validations>) {
self.value.formRemainder(dividingBy: other.value)
}
/// See [`FloatingPoint.formSquareRoot()`](https://developer.apple.com/documentation/swift/floatingpoint/2299104-formsquareroot).
public mutating func formSquareRoot() {
self.value.formSquareRoot()
}
/// See [`FloatingPoint.formTruncatingRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/1846470-formtruncatingremainder).
public mutating func formTruncatingRemainder(dividingBy other: Failable<T, Validations>) {
self.value.formTruncatingRemainder(dividingBy: other.value)
}
/// See [`FloatingPoint.isEqual(to:)`](https://developer.apple.com/documentation/swift/floatingpoint/1846385-isequal).
public func isEqual(to other: Failable<T, Validations>) -> Bool {
return self.value.isEqual(to: other.value)
}
/// See [`FloatingPoint.isLess(than:)`](https://developer.apple.com/documentation/swift/floatingpoint/1849403-isless).
public func isLess(than other: Failable<T, Validations>) -> Bool {
return self.value.isLess(than: other.value)
}
/// See [`FloatingPoint.isLessThanOrEqualTo(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1849007-islessthanorequalto).
public func isLessThanOrEqualTo(_ other: Failable<T, Validations>) -> Bool {
return self.value.isLessThanOrEqualTo(other.value)
}
/// See [`FloatingPoint.isTotallyOrdered(belowOrEqualTo:)`](https://developer.apple.com/documentation/swift/floatingpoint/2428057-istotallyordered).
public func isTotallyOrdered(belowOrEqualTo other: Failable<T, Validations>) -> Bool {
return self.value.isTotallyOrdered(belowOrEqualTo: other.value)
}
/// See [`FloatingPoint.negate()`](https://developer.apple.com/documentation/swift/floatingpoint/1849560-negate).
public mutating func negate() {
self.value.negate()
}
/// See [`FloatingPoint.remainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017981-remainder).
public func remainder(dividingBy other: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(self.value.remainder(dividingBy: other.value))
}
/// See [`FloatingPoint.round()`](https://developer.apple.com/documentation/swift/floatingpoint/2297801-round).
public mutating func round() {
self.value.round()
}
/// See [`FloatingPoint.round(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2298113-round).
public mutating func round(_ rule: FloatingPointRoundingRule) {
self.value.round(rule)
}
/// See [`FloatingPoint.rounded()`](https://developer.apple.com/documentation/swift/floatingpoint/2295900-rounde).
public func rounded()throws -> Failable<T, Validations> {
return try Failable(self.value.rounded())
}
/// See [`FloatingPoint.rounded(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017985-rounded).
public func rounded(_ rule: FloatingPointRoundingRule)throws -> Failable<T, Validations> {
return try Failable(self.value.rounded(rule))
}
/// See [`FloatingPoint.squareRoot()`](https://developer.apple.com/documentation/swift/floatingpoint/3017991-squareroot).
public func squareRoot()throws -> Failable<T, Validations> {
return try Failable(self.value.squareRoot())
}
/// See [`FloatingPoint.truncatingRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017995-truncatingremainder).
public func truncatingRemainder(dividingBy other: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(self.value.truncatingRemainder(dividingBy: other.value))
}
// --- Validtion Flexibility ---
/// See [`FloatingPoint.addProduct(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2295205-addproduct).
public mutating func addProduct<V1, V2>(_ lhs: Failable<T, V1>, _ rhs: Failable<T, V2>) {
self.value.addProduct(lhs.value, rhs.value)
}
/// See [`FloatingPoint.addingProduct(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017959-addingproduct).
public func addingProduct<V1, V2>(_ lhs: Failable<T, V1>, _ rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> {
return try Failable<T, AppendedValidations<T, V1, V2>>(self.value.addingProduct(lhs.value, rhs.value))
}
/// See [`FloatingPoint.formRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/2299459-formremainder).
public mutating func formRemainder<V>(dividingBy other: Failable<T, V>) {
self.value.formRemainder(dividingBy: other.value)
}
/// See [`FloatingPoint.formTruncatingRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/1846470-formtruncatingremainder).
public mutating func formTruncatingRemainder<V>(dividingBy other: Failable<T, V>) {
self.value.formTruncatingRemainder(dividingBy: other.value)
}
/// See [`FloatingPoint.isEqual(to:)`](https://developer.apple.com/documentation/swift/floatingpoint/1846385-isequal).
public func isEqual<V>(to other: Failable<T, V>) -> Bool {
return self.value.isEqual(to: other.value)
}
/// See [`FloatingPoint.isLess(than:)`](https://developer.apple.com/documentation/swift/floatingpoint/1849403-isless).
public func isLess<V>(than other: Failable<T, V>) -> Bool {
return self.value.isLess(than: other.value)
}
/// See [`FloatingPoint.isLessThanOrEqualTo(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1849007-islessthanorequalto).
public func isLessThanOrEqualTo<V>(_ other: Failable<T, V>) -> Bool {
return self.value.isLessThanOrEqualTo(other.value)
}
/// See [`FloatingPoint.isTotallyOrdered(belowOrEqualTo:)`](https://developer.apple.com/documentation/swift/floatingpoint/2428057-istotallyordered).
public func isTotallyOrdered<V>(belowOrEqualTo other: Failable<T, V>) -> Bool {
return self.value.isTotallyOrdered(belowOrEqualTo: other.value)
}
/// See [`FloatingPoint.remainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017981-remainder).
public func remainder<V>(dividingBy other: Failable<T, V>)throws -> Failable<T, AppendedValidations<T, Validations, V>> {
return try Failable<T, AppendedValidations<T, Validations, V>>(self.value.remainder(dividingBy: other.value))
}
// See [`FloatingPoint.truncatingRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017995-truncatingremainder).
public func truncatingRemainder<V>(dividingBy other: Failable<T, V>)throws -> Failable<T, AppendedValidations<T, Validations, V>> {
return try Failable<T, AppendedValidations<T, Validations, V>>(self.value.truncatingRemainder(dividingBy: other.value))
}
// MARK: - Static Methods
/// See [`FloatingPoint.maximum(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017963-maximum).
public static func maximum(_ x: Failable<T, Validations>, _ y: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(T.maximum(x.value, y.value))
}
/// See [`FloatingPoint.maximumMagnitude(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017967-maximummagnitude).
public static func maximumMagnitude(_ x: Failable<T, Validations>, _ y: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(T.maximumMagnitude(x.value, y.value))
}
/// See [`FloatingPoint.minimum(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017971-minimum).
public static func minimum(_ x: Failable<T, Validations>, _ y: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(T.minimum(x.value, y.value))
}
/// See [`FloatingPoint.minimumMagnitude(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017975-minimummagnitude).
public static func minimumMagnitude(_ x: Failable<T, Validations>, _ y: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(T.minimumMagnitude(x.value, y.value))
}
/// See [`FloatingPoint.maximum(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017963-maximum).
public static func maximum<V1, V2>(_ x: Failable<T, V1>, _ y: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> {
return try Failable<T, AppendedValidations<T, V1, V2>>(T.maximum(x.value, y.value))
}
/// See [`FloatingPoint.maximumMagnitude(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017967-maximummagnitude).
public static func maximumMagnitude<V1, V2>(_ x: Failable<T, V1>, _ y: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> {
return try Failable<T, AppendedValidations<T, V1, V2>>(T.maximumMagnitude(x.value, y.value))
}
/// See [`FloatingPoint.minimum(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017971-minimum).
public static func minimum<V1, V2>(_ x: Failable<T, V1>, _ y: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> {
return try Failable<T, AppendedValidations<T, V1, V2>>(T.minimum(x.value, y.value))
}
/// See [`FloatingPoint.minimumMagnitude(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/3017975-minimummagnitude).
public static func minimumMagnitude<V1, V2>(_ x: Failable<T, V1>, _ y: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> {
return try Failable<T, AppendedValidations<T, V1, V2>>(T.minimumMagnitude(x.value, y.value))
}
// MARK: - Operators
/// See [`FloatingPoint.<(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2883927).
public static func < (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value < rhs.value
}
/// See [`FloatingPoint.<=(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2884778).
public static func <= (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value <= rhs.value
}
/// See [`FloatingPoint.>(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2885368).
public static func > (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value > lhs.value
}
/// See [`FloatingPoint.>(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2884837).
public static func >= (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Bool {
return lhs.value >= lhs.value
}
/// See [`FloatingPoint.*(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2886135).
public static func * (_ lhs: Failable<T, Validations>, _ rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value * rhs.value)
}
/// See [`FloatingPoint.*=(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2885700).
public static func *= (_ lhs: inout Failable<T, Validations>, _ rhs: Failable<T, Validations>)throws {
try lhs = lhs * rhs
}
/// See [`FloatingPoint.+(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2885022).
public static func + (_ lhs: Failable<T, Validations>, _ rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value + rhs.value)
}
/// See [`FloatingPoint.+=(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2884273).
public static func += (_ lhs: inout Failable<T, Validations>, _ rhs: Failable<T, Validations>)throws {
try lhs = lhs + rhs
}
/// See [`FloatingPoint.-(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2884257).
public prefix static func - (_ x: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(-x.value)
}
/// See [`FloatingPoint.-(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2885455).
public static func - (_ lhs: Failable<T, Validations>, _ rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value - rhs.value)
}
/// See [`FloatingPoint.-=(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2884054).
public static func -= (_ lhs: inout Failable<T, Validations>, _ rhs: Failable<T, Validations>)throws {
try lhs = lhs - rhs
}
/// See [`FloatingPoint./(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2884057).
public static func / (_ lhs: Failable<T, Validations>, _ rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value / rhs.value)
}
/// See [`FloatingPoint./=(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2886632).
public static func /= (_ lhs: inout Failable<T, Validations>, _ rhs: Failable<T, Validations>)throws {
try lhs = lhs + rhs
}
/// See [`FloatingPoint.==(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2919612).
public static func == (_ lhs: Failable<T, Validations>, _ rhs: Failable<T, Validations>) -> Bool {
return lhs.value == rhs.value
}
}
public func < <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: FloatingPoint {
return lhs.value < rhs.value
}
public func <= <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: FloatingPoint {
return lhs.value <= rhs.value
}
public func > <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: FloatingPoint {
return lhs.value > lhs.value
}
public func >= <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool where T: FloatingPoint {
return lhs.value >= lhs.value
}
/// Multiplies two `Failable` values and produces their product, rounding to a representable value.
///
/// - Parameters:
/// - lhs: The left value to multiply.
/// - rhs: The right value to multiply.
///
/// - Returns: The product of the multiplcation equation, where the validation is the validations of the two values passed in.
public func * <T, V1, V2>(_ lhs: Failable<T, V1>, _ rhs: Failable<T, V2>)throws
-> Failable<T, AppendedValidations<T, V1, V2>> where T: FloatingPoint
{
return try Failable(lhs.value * rhs.value)
}
/// Adds two `Failable` values and produces their sum, rounding to a representable value.
///
/// - Parameters:
/// - lhs: The left value to add.
/// - rhs: The right value to add.
///
/// - Returns: The sum of the addition equation, where the validation is the validations of the two values passed in.
public func + <T, V1, V2>(_ lhs: Failable<T, V1>, _ rhs: Failable<T, V2>)throws
-> Failable<T, AppendedValidations<T, V1, V2>> where T: FloatingPoint
{
return try Failable(lhs.value + rhs.value)
}
/// Subtracts two `Failable` values and produces their difference, rounding to a representable value.
///
/// - Parameters:
/// - lhs: The value to subtract from.
/// - rhs: The value to subtract from the left value.
///
/// - Returns: The difference of the subtraction equation, where the validation is the validations of the two values passed in.
public func - <T, V1, V2>(_ lhs: Failable<T, V1>, _ rhs: Failable<T, V2>)throws
-> Failable<T, AppendedValidations<T, V1, V2>> where T: FloatingPoint
{
return try Failable(lhs.value - rhs.value)
}
/// Divides two `Failable` values and produces their quotient, rounding to a representable value.
///
/// - Parameters:
/// - lhs: The value to subtract from.
/// - rhs: The value to subtract from the left value.
///
/// - Returns: The quotient of the division equation, where the validation is the validations of the two values passed in.
public func / <T, V1, V2>(_ lhs: Failable<T, V1>, _ rhs: Failable<T, V2>)throws
-> Failable<T, AppendedValidations<T, V1, V2>> where T: FloatingPoint
{
return try Failable(lhs.value / rhs.value)
}
/// Returns a Boolean value indicating whether two values are equal.
///
/// - Parameters:
/// - lhs: The left value to check for equality.
/// - rhs: The right value to check for euqality.
///
/// - Returns: The boolean indicating whether the values are equal or not.
public func == <T, V1, V2>(_ lhs: Failable<T, V1>, _ rhs: Failable<T, V2>) -> Bool where T: FloatingPoint {
return lhs.value == rhs.value
}

View File

@ -1,7 +0,0 @@
extension Failable: Hashable where T: Hashable {
/// See [`Hashable.hash(into:)`](https://developer.apple.com/documentation/swift/hashable/2995575-hash).
public func hash(into hasher: inout Hasher) {
hasher.combine(self.value)
}
}

View File

@ -1,178 +0,0 @@
extension Failable where T: Numeric {
/// See [`Numeric.Magnitude`](https://developer.apple.com/documentation/swift/numeric/2884423-magnitude).
public typealias Magnitude = T.Magnitude
/// See [`Numeric.init(exactly:)`](https://developer.apple.com/documentation/swift/numeric/2886795-init).
public init?<B>(exactly source: B) where B : BinaryInteger {
guard let t = T(exactly: source) else { return nil }
do {
try self.init(t)
} catch { return nil }
}
/// See [`Numeric.magnitude`](https://developer.apple.com/documentation/swift/numeric/2884876-magnitude).
public var magnitude: T.Magnitude {
return self.value.magnitude
}
/// See [`Numeric.*(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2883821).
public static func * (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value * rhs.value)
}
/// See [`Numeric.*=(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2886882).
public static func *= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs <~ lhs.value * rhs.value
}
/// See [`Numeric.+(_:)`]https://developer.apple.com/documentation/swift/numeric/2886206).
public static prefix func + (lhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return lhs
}
/// See [`Numeric.+(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2884921).
public static func + (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value + rhs.value)
}
/// See [`Numeric.+=(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2885744).
public static func += (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs <~ lhs.value + rhs.value
}
/// See [`Numeric.-(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2885464).
public static func - (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(lhs.value - rhs.value)
}
/// See [`Numeric.-=(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2884360).
public static func -= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>)throws {
try lhs <~ lhs.value - rhs.value
}
}
/// Multiplies two values from `Failable` instances and produces their product, combining the validations.
///
/// - Parameters:
/// - lhs: The left value to multiply.
/// - rhs: The right value to multiply.
///
/// - Returns: The product of the `value` values from the two `Failable` instances.
/// The validations for the new `Failalbe` value is a combination of the validations from both instances.
public func * <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: Numeric {
return try Failable(lhs.value * rhs.value)
}
/// Multiplies two values from `Failable` instances and stores the result in the left-hand-side `Failable` instance.
///
/// - Parameters:
/// - lhs: The left value to multiply.
/// - rhs: The right value to multiply.
public func *= <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>)throws where T: Numeric {
try lhs <~ lhs.value * rhs.value
}
/// Adds two values from `Failable` instances and produces their sum, combining the validations.
///
/// - Parameters:
/// - lhs: The left value to add.
/// - rhs: The right value to add.
///
/// - Returns: The sum of the `value` values from the two `Failable` instances.
/// The validations for the new `Failalbe` value is a combination of the validations from both instances.
public func + <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: Numeric {
return try Failable(lhs.value + rhs.value)
}
/// Adds two values from `Failable` instances and stores the result in the left-hand-side `Failable` instance.
///
/// - Parameters:
/// - lhs: The left value to add.
/// - rhs: The right value to add.
public func += <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>)throws where T: Numeric {
try lhs <~ lhs.value + rhs.value
}
/// Subtracts one `Failable` value from another and produces their difference, combining the validations.
///
/// - Parameters:
/// - lhs: The value to subtract from.
/// - rhs: The value to subtract.
///
/// - Returns: The product of the `value` values from the two `Failable` instances.
/// The validations for the new `Failalbe` value is a combination of the validations from both instances.
public func - <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>)throws -> Failable<T, AppendedValidations<T, V1, V2>> where T: Numeric {
return try Failable(lhs.value - rhs.value)
}
/// Subtracts one `Failable` value from another and stores the result in the left-hand-side `Failable` instance.
///
/// - Parameters:
/// - lhs: The value to subtract from.
/// - rhs: The value to subtract.
public func -= <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>)throws where T: Numeric {
try lhs <~ lhs.value - rhs.value
}
/// Multiplies a `Failable` value with another `T` value and produces their product.
///
/// - Parameters:
/// - lhs: The left value to multiply.
/// - rhs: The right value to multiply.
///
/// - Returns: The product of the `Failable.value` property and the `rhs` value.
public func * <T, V1>(lhs: Failable<T, V1>, rhs: T)throws -> Failable<T, V1> where T: Numeric {
return try Failable(lhs.value * rhs)
}
/// Multiplies a `Failable` value with another `T` value and stores the result in the left-hand-side `Failable` instance.
///
/// - Parameters:
/// - lhs: The left value to multiply.
/// - rhs: The right value to multiply.
public func *= <T, V1>(lhs: inout Failable<T, V1>, rhs: T)throws where T: Numeric {
try lhs <~ lhs.value * rhs
}
/// Adds a `Failable` value to another `T` value and produces their sum.
///
/// - Parameters:
/// - lhs: The left value to add.
/// - rhs: The right value to add.
///
/// - Returns: The sum of the `Failable.value` property and the `rhs` value.
public func + <T, V1>(lhs: Failable<T, V1>, rhs: T)throws -> Failable<T, V1> where T: Numeric {
return try Failable(lhs.value + rhs)
}
/// Adds a `Failable` value to another `T` value and stores the result in the left-hand-side `Failable` instance.
///
/// - Parameters:
/// - lhs: The left value to add.
/// - rhs: The right value to add.
public func += <T, V1>(lhs: inout Failable<T, V1>, rhs: T)throws where T: Numeric {
try lhs <~ lhs.value + rhs
}
/// Subtracts `T` value from a `Failable` value and produces their difference.
///
/// - Parameters:
/// - lhs: The value to subtract from.
/// - rhs: The value to subtract.
///
/// - Returns: The difference of the `Failable.value` property and the `rhs` value.
public func - <T, V1>(lhs: Failable<T, V1>, rhs: T)throws -> Failable<T, V1> where T: Numeric {
return try Failable(lhs.value - rhs)
}
/// Subtracts a `T` value from a `Failable` value and stores the result in the left-hand-side `Failable` instance.
///
/// - Parameters:
/// - lhs: The value to subtract from.
/// - rhs: The value to subtract.
public func -= <T, V1>(lhs: inout Failable<T, V1>, rhs: T)throws where T: Numeric {
try lhs <~ lhs.value - rhs
}

View File

@ -1,36 +0,0 @@
extension Failable {
/// See [`Optional.map(_:)`](https://developer.apple.com/documentation/swift/optional/1539476-map).
public func map<U, Wrapped>(_ transform: (Wrapped) throws -> U) rethrows -> U? where T == Optional<Wrapped> {
return try self.value.map(transform)
}
/// See [`Optional.flatMap(_:)`](https://developer.apple.com/documentation/swift/optional/1540500-flatmap).
public func flatMap<U, Wrapped>(_ transform: (Wrapped) throws -> U?) rethrows -> U? where T == Optional<Wrapped> {
return try self.value.flatMap(transform)
}
/// See [`Optional.==(_:_:)`](https://developer.apple.com/documentation/swift/optional/2950146).
public static func == <Wrapped>(lhs: Failable<Wrapped?, Validations>, rhs: Failable<Wrapped?, Validations>)
-> Bool where T == Optional<Wrapped>, Wrapped: Equatable
{
return lhs.value == rhs.value
}
/// See [`Optional.!=(_:_:)`](https://developer.apple.com/documentation/swift/optional/2949565).
public static func != <Wrapped>(lhs: Failable<Wrapped?, Validations>, rhs: Failable<Wrapped?, Validations>)
-> Bool where T == Optional<Wrapped>, Wrapped: Equatable
{
return lhs.value != rhs.value
}
}
/// See [`Optional.??(_:_:)`](https://developer.apple.com/documentation/swift/1539917).
public func ?? <T, V>(optional: Failable<T?, V>, defaultValue: @autoclosure () throws -> T) rethrows -> T {
return try optional.value ?? defaultValue()
}
/// See [`Optional.??(_:_:)`](https://developer.apple.com/documentation/swift/1541015).
public func ?? <T, V>(optional: Failable<T?, V>, defaultValue: @autoclosure () throws -> T?) rethrows -> T? {
return try optional.value ?? defaultValue()
}

View File

@ -1,33 +0,0 @@
extension Failable: RawRepresentable where T: RawRepresentable {
/// See [`RawRepresentable.RawValue`](https://developer.apple.com/documentation/swift/rawrepresentable/1540809-rawvalue).
public typealias RawValue = T.RawValue
/// See [`RawRepresentable.init(rawValue:)`](https://developer.apple.com/documentation/swift/rawrepresentable/1538354-init).
///
/// If the `Failable` initializer throws an error, this initializer will return `nil`.
public init?(rawValue: T.RawValue) {
guard let value = T(rawValue: rawValue) else { return nil }
do {
try self.init(value)
} catch {
return nil
}
}
/// See [`RawRepresentable.rawValue`](https://developer.apple.com/documentation/swift/rawrepresentable/1540698-rawvalue).
public var rawValue: T.RawValue {
return self.value.rawValue
}
}
extension Failable where T: CaseIterable {
/// See [`CaseIterable.AllCases`](https://developer.apple.com/documentation/swift/caseiterable/2994868-allcases).
public typealias AllCases = T.AllCases
/// See [`CaseIterable.allCases`](https://developer.apple.com/documentation/swift/caseiterable/2994869-allcases).
public static var allCases: T.AllCases {
return T.allCases
}
}

View File

@ -1,49 +0,0 @@
extension Failable: Sequence where T: Sequence {
/// See [`Sequence.Element`](https://developer.apple.com/documentation/swift/sequence/2908099-element).
public typealias Element = T.Element
// See [`Sequence.Iterator`](https://developer.apple.com/documentation/swift/sequence/1641120-iterator).
public typealias Iterator = T.Iterator
/// See [`Sequence.makeIterator()`](https://developer.apple.com/documentation/swift/sequence/2885155-makeiterator).
public func makeIterator() -> T.Iterator {
return self.value.makeIterator()
}
/// See [`Sequence.split(separator:maxSplits:omittingEmptySubsequences:)`](https://developer.apple.com/documentation/swift/sequence/2908109-split).
public func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (T.Element) throws -> Bool) rethrows
-> [ArraySlice<T.Element>]
{
return try self.value.split(maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: isSeparator)
}
/// See [`Sequence.suffix(_:)`](https://developer.apple.com/documentation/swift/sequence/2965540-suffix).
public func suffix(_ maxLength: Int) -> [T.Element] {
return self.value.suffix(maxLength)
}
/// See [`Sequence.prefix(while:)`](https://developer.apple.com/documentation/swift/sequence/2965528-prefix)
public func prefix(while predicate: (T.Element) throws -> Bool) rethrows -> [T.Element] {
return try self.value.prefix(while: predicate)
}
/// See [`Sequence.prefix(_:)`](https://developer.apple.com/documentation/swift/sequence/2965524-prefix).
public func prefix(_ maxLength: Int) -> PrefixSequence<T> {
return self.value.prefix(maxLength)
}
/// See [`Sequence.drop(while:)`](https://developer.apple.com/documentation/swift/sequence/2965501-drop).
public func drop(while predicate: (T.Element) throws -> Bool) rethrows -> DropWhileSequence<T> {
return try self.value.drop(while: predicate)
}
/// See [`Sequence.dropLast`](https://developer.apple.com/documentation/swift/sequence/2965508-droplast).
public func dropLast(_ k: Int) -> [T.Element] {
return self.value.dropLast(k)
}
/// See [`Sequence.dropFirst(_:)`](https://developer.apple.com/documentation/swift/sequence/2965504-dropfirst).
public func dropFirst(_ k: Int) -> DropFirstSequence<T> {
return self.value.dropFirst(k)
}
}

View File

@ -1,12 +0,0 @@
extension Failable where T: SignedNumeric {
/// See [`SignedNumeric.negate()`](https://developer.apple.com/documentation/swift/signednumeric/2883859-negate).
public mutating func negate()throws {
try self = -self
}
/// See [`SignedNumeric.-(_:)`](https://developer.apple.com/documentation/swift/signednumeric/2965579).
public static prefix func - (lhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try Failable(-lhs.value)
}
}

View File

@ -1,56 +0,0 @@
extension Failable where T: Strideable {
/// See [`Strideable.Stride`](https://developer.apple.com/documentation/swift/strideable/1541220-stride).
public typealias Stride = T.Stride
/// See [`Strideable.advance(by:)`](https://developer.apple.com/documentation/swift/strideable/1641148-advanced).
public func advance(by n: Stride)throws -> Failable<T, Validations> {
return try Failable(self.value.advanced(by: n))
}
/// See [`Strideable.distance(to:)`](https://developer.apple.com/documentation/swift/strideable/1641148-advanced).
public func distance(to other: Failable<T, Validations>) -> Stride {
return self.value.distance(to: other.value)
}
/// See [`Strideable.+(_:_:)`](https://developer.apple.com/documentation/swift/strideable/2885404).
public static func + (lhs: Failable<T, Validations>, rhs: Stride)throws -> Failable<T, Validations> {
return try lhs.advance(by: rhs)
}
/// See [`Strideable.+(_:_:)`](https://developer.apple.com/documentation/swift/strideable/2886679).
public static func + (lhs: Stride, rhs: Failable<T, Validations>)throws -> Failable<T, Validations> {
return try rhs.advance(by: lhs)
}
/// See [`Strideable.+=(_:_:)`](https://developer.apple.com/documentation/swift/strideable/2884440).
public static func += (lhs: inout Failable<T, Validations>, rhs: Stride)throws {
try lhs <~ lhs.advance(by: rhs).value
}
/// See [`Strideable.-(_:_:)`](https://developer.apple.com/documentation/swift/strideable/2884623).
public static func - (lhs: Failable<T, Validations>, rhs: Stride)throws -> Failable<T, Validations> {
return try lhs.advance(by: -rhs)
}
/// See [`Strideable.-(_:_:)`](https://developer.apple.com/documentation/swift/strideable/2886160).
public static func - (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Stride {
return rhs.distance(to: lhs)
}
/// See [`Strideable.-=(_:_:)`](https://developer.apple.com/documentation/swift/strideable/2885177).
public static func -= (lhs: inout Failable<T, Validations>, rhs: Stride)throws {
try lhs <~ lhs.advance(by: -rhs).value
}
}
extension Failable where T: Strideable, T.Stride: SignedInteger {
/// See [`Stridable....(_:_:)`](https://developer.apple.com/documentation/swift/strideable/2950083).
public static func ... (
lhs: Failable<T, Validations>,
rhs: Failable<T, Validations>
)throws -> Failable<ClosedRange<T>, ElementValidation<ClosedRange<T>, Validations>> {
return try (lhs.value...rhs.value).failable()
}
}

View File

@ -1,9 +0,0 @@
extension Failable where T: UnsignedInteger {
/// See [`UnsignedInteger.magnitude`](https://developer.apple.com/documentation/swift/unsignedinteger/2884378-magnitude)
///
/// - Warning: This property has no failing options, so your program will crash if it produces a value that does not pass validation.g
public var magnitude: Failable<T, Validations> {
return try! Failable(self.value.magnitude)
}
}

View File

@ -0,0 +1,129 @@
public struct MagnitudeValidation<Magnitude>: Validation where Magnitude: Numeric & Comparable {
public typealias Supported = Magnitude
public static func validate(_ value: Magnitude)throws {
guard value >= Magnitude.zero else {
throw ValidationError(
identifier: "invalidMagnitude",
reason: "A number's magnitude must be a valid absolute value, i.e. never negative."
)
}
}
}
extension Failable: Strideable where T: Strideable {
/// See [`Strideable.Stride`](https://developer.apple.com/documentation/swift/strideable/1541220-stride).
public typealias Stride = Failable<T.Stride, EmptyValidation<T.Stride>>
/// See [`Strideable.advanced(by:)`](https://developer.apple.com/documentation/swift/strideable/1641148-advanced).
public func advanced(by n: Stride) -> Failable<T, Validations> {
return Failable.map(self, n) { start, stride in return start.advanced(by: stride) }
}
/// See [`Strideable.distance(to:)`](https://developer.apple.com/documentation/swift/strideable/1641775-distance).
public func distance(to other: Failable<T, Validations>) -> Stride {
return Failable.map(self, other) { start, end in start.distance(to: end) }
}
}
extension Failable: AdditiveArithmetic where T: AdditiveArithmetic {
/// See [`AdditiveArithmetic.zero`](https://developer.apple.com/documentation/swift/additivearithmetic/3126829-zero).
public static var zero: Failable<T, Validations> {
return Failable(T.zero)
}
/// See [`AdditiveArithmetic.-(_:_:)`](https://developer.apple.com/documentation/swift/additivearithmetic/3126825).
public static func - (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs) { left, right in left - right }
}
/// See [`AdditiveArithmetic.+(_:_:)`](https://developer.apple.com/documentation/swift/additivearithmetic/3126821).
public static func + (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs) { left, right in left + right }
}
/// See [`AdditiveArithmetic.-=(_:_:)`](https://developer.apple.com/documentation/swift/additivearithmetic/3126828).
public static func -= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs - rhs
}
/// See [`AdditiveArithmetic.+=(_:_:)`](https://developer.apple.com/documentation/swift/additivearithmetic/3126824).
public static func += (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs + rhs
}
}
extension Failable: Numeric where T: Numeric {
/// See [`Numeric.Magnitude`](https://developer.apple.com/documentation/swift/numeric/2884423-magnitude).
public typealias Magnitude = Failable<T.Magnitude, MagnitudeValidation<T.Magnitude>>
/// See [`Numeric.magnitude`](https://developer.apple.com/documentation/swift/numeric/2884876-magnitude).
public var magnitude: Magnitude {
return self.map { $0.magnitude }
}
/// See [`Numeric.init(exactly:)`](https://developer.apple.com/documentation/swift/numeric/2886795-init).
public init?<N>(exactly source: N) where N : BinaryInteger {
guard let value = T(exactly: source) else { return nil }
self.init(value)
}
/// See [`Numeric.*(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2883821).
public static func * (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs, closure: { left, right in left * right })
}
/// See [`Numeric.*=(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2886882).
public static func *= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs * rhs
}
}
extension Failable: SignedNumeric where T: SignedNumeric {
/// See [`SignedNumeric.negate()`](https://developer.apple.com/documentation/swift/signednumeric/2883859-negate).
public mutating func negate() {
self.value?.negate()
}
/// See [`SignedNumeric.-(_:)`](https://developer.apple.com/documentation/swift/signednumeric/2965579).
public static prefix func - (lhs: Failable<T, Validations>) -> Failable<T, Validations> {
guard let value = lhs.value else { return lhs }
return Failable<T, Validations>(-value)
}
}
/// See [`AdditiveArithmetic.-(_:_:)`](https://developer.apple.com/documentation/swift/additivearithmetic/3126825).
public func - <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Failable<T, AppendedValidations<V1, V2>>
where T: AdditiveArithmetic
{
return Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left - right }
}
/// See [`AdditiveArithmetic.+(_:_:)`](https://developer.apple.com/documentation/swift/additivearithmetic/3126821).
public func + <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Failable<T, AppendedValidations<V1, V2>>
where T: AdditiveArithmetic
{
return Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left + right }
}
/// See [`Numeric.*(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2883821).
public func * <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Failable<T, AppendedValidations<V1, V2>>
where T: Numeric
{
return Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left * right }
}
/// See [`AdditiveArithmetic.-=(_:_:)`](https://developer.apple.com/documentation/swift/additivearithmetic/3126828).
public func -= <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>) where T: AdditiveArithmetic {
lhs = Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left - right }
}
/// See [`AdditiveArithmetic.+=(_:_:)`](https://developer.apple.com/documentation/swift/additivearithmetic/3126824).
public func += <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>) where T: AdditiveArithmetic {
lhs = Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left + right }
}
/// See [`Numeric.*=(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2886882).
public func *= <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>) where T: Numeric {
lhs = Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left * right }
}

View File

@ -0,0 +1,275 @@
// TODO: Try to remove `Validations == MagnitudeValidation<T>` constraint.
extension Failable: FloatingPoint where T: FloatingPoint, Validations == MagnitudeValidation<T> {
/// See [`FloatingPoint.Exponent`](https://developer.apple.com/documentation/swift/floatingpoint/1848224-exponent).
public typealias Exponent = Failable<T.Exponent, EmptyValidation<T.Exponent>>
/// See [`FloatingPoint.nan`](https://developer.apple.com/documentation/swift/floatingpoint/1641652-nan).
public static var nan: Failable<T, Validations> {
return Failable(T.nan)
}
/// See [`FloatingPoint.signalingNaN`](https://developer.apple.com/documentation/swift/floatingpoint/1845864-signalingnan).
public static var signalingNaN: Failable<T, Validations> {
return Failable(T.signalingNaN)
}
/// See [`FloatingPoint.infinity`](https://developer.apple.com/documentation/swift/floatingpoint/1641304-infinity).
public static var infinity: Failable<T, Validations> {
return Failable(T.infinity)
}
/// See [`FloatingPoint.greatestFiniteMagnitude`](https://developer.apple.com/documentation/swift/floatingpoint/1849534-greatestfinitemagnitude).
public static var greatestFiniteMagnitude: Failable<T, Validations> {
return Failable(T.greatestFiniteMagnitude)
}
/// See [`FloatingPoint.pi`](https://developer.apple.com/documentation/swift/floatingpoint/1845454-pi).
public static var pi: Failable<T, Validations> {
return Failable(T.pi)
}
/// See [`FloatingPoint.leastNormalMagnitude`](https://developer.apple.com/documentation/swift/floatingpoint/1849504-leastnormalmagnitude).
public static var leastNormalMagnitude: Failable<T, Validations> {
return Failable(T.leastNormalMagnitude)
}
/// See [`FloatingPoint.leastNonzeroMagnitude`](https://developer.apple.com/documentation/swift/floatingpoint/1848591-leastnonzeromagnitude).
public static var leastNonzeroMagnitude: Failable<T, Validations> {
return Failable(T.leastNonzeroMagnitude)
}
/// See [`FloatingPoint.radix`](https://developer.apple.com/documentation/swift/floatingpoint/1846156-radix).
public static var radix: Int {
return T.radix
}
/// See [`FloatingPoint.ulp`](https://developer.apple.com/documentation/swift/floatingpoint/1847492-ulp).
public var ulp: Failable<T, Validations> {
return self[keyPath: \.ulp]
}
/// See [`FloatingPoint.sign`](https://developer.apple.com/documentation/swift/floatingpoint/1847735-sign).
public var sign: FloatingPointSign {
return self.value?.sign ?? .plus
}
/// See [`FloatingPoint.exponent`](https://developer.apple.com/documentation/swift/floatingpoint/1846275-exponent).
public var exponent: Failable<T.Exponent, EmptyValidation<T.Exponent>> {
return self[keyPath: \.exponent]
}
/// See [`FloatingPoint.significand`](https://developer.apple.com/documentation/swift/floatingpoint/1847298-significand).
public var significand: Failable<T, Validations> {
return self[keyPath: \.significand]
}
/// See [`FloatingPoint.nextUp`](https://developer.apple.com/documentation/swift/floatingpoint/1848104-nextup).
public var nextUp: Failable<T, Validations> {
return self[keyPath: \.nextUp]
}
/// See [`FloatingPoint.isNormal`](https://developer.apple.com/documentation/swift/floatingpoint/1641394-isnormal).
public var isNormal: Bool {
return self.value?.isNormal ?? false
}
/// See [`FloatingPoint.isFinite`](https://developer.apple.com/documentation/swift/floatingpoint/1641190-isfinite).
public var isFinite: Bool {
return self.value?.isFinite ?? false
}
/// See [`FloatingPoint.isZero`](https://developer.apple.com/documentation/swift/floatingpoint/1641514-iszero).
public var isZero: Bool {
return self.value?.isZero ?? false
}
/// See [`FloatingPoint.isSubnormal`](https://developer.apple.com/documentation/swift/floatingpoint/1641181-issubnormal).
public var isSubnormal: Bool {
return self.value?.isSubnormal ?? false
}
/// See [`FloatingPoint.isInfinite`](https://developer.apple.com/documentation/swift/floatingpoint/1641669-isinfinite).
public var isInfinite: Bool {
return self.value?.isInfinite ?? false
}
/// See [`FloatingPoint.isNaN`](https://developer.apple.com/documentation/swift/floatingpoint/1641763-isnan).
public var isNaN: Bool {
return self.value?.isNaN ?? false
}
/// See [`FloatingPoint.isSignalingNaN`](https://developer.apple.com/documentation/swift/floatingpoint/1847971-issignalingnan).
public var isSignalingNaN: Bool {
return self.value?.isSignalingNaN ?? false
}
/// See [`FloatingPoint.isCanonical`](https://developer.apple.com/documentation/swift/floatingpoint/1847929-iscanonical).
public var isCanonical: Bool {
return self.value?.isCanonical ?? false
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1641560-init).
public init(_ value: Int) {
self = Failable(T(value))
}
/// See [`FloatingPoint.init(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2964416-init).
public init<Source>(_ value: Source) where Source : BinaryInteger {
self = Failable(T(value))
}
/// See [`FloatingPoint.init(sign:exponent:significand:`](https://developer.apple.com/documentation/swift/floatingpoint/1845755-init).
public init(sign: FloatingPointSign, exponent: Exponent, significand: Failable<T, Validations>) {
self = Failable.map(exponent, significand) { exp, sig in T(sign: sign, exponent: exp, significand: sig)}
}
/// See [`FloatingPoint.init(signOf:magnitudeOf:)`](https://developer.apple.com/documentation/swift/floatingpoint/1849294-init).
public init(signOf sign: Failable<T, Validations>, magnitudeOf maginitude: Failable<T, Validations>) {
self = Failable.map(sign, maginitude, closure: T.init(signOf:magnitudeOf:))
}
/// See [`FloatingPoint.*(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2886135).
public static func * (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs) { left, right in left * right }
}
/// See [`FloatingPoint.*=(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2885700).
public static func *= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs * rhs
}
/// See [`FloatingPoint./(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2884057).
public static func / (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs) { left, right in left / right }
}
/// See [`FloatingPoint./=(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2886632).
public static func /= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs / rhs
}
/// See [`FloatingPoint.round(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2298113-round).
public mutating func round(_ rule: FloatingPointRoundingRule) {
self = self.map { value in value.rounded(rule) }
}
/// See [`FloatingPoint.formRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/2299459-formremainder).
public mutating func formRemainder(dividingBy other: Failable<T, Validations>) {
self = Failable.map(self, other) { left, right in
var result = left
result.formRemainder(dividingBy: right)
return result
}
}
/// See [`FloatingPoint.formTruncatingRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/floatingpoint/1846470-formtruncatingremainder).
public mutating func formTruncatingRemainder(dividingBy other: Failable<T, Validations>) {
self = Failable.map(self, other) { left, right in
var result = left
result.formTruncatingRemainder(dividingBy: right)
return result
}
}
/// See [`FloatingPoint.formSquareRoot()`](https://developer.apple.com/documentation/swift/floatingpoint/2299104-formsquareroot).
public mutating func formSquareRoot() {
self = self.map { value in
var result = value
result.formSquareRoot()
return result
}
}
/// See [`FloatingPoint.addProduct(_:_:)`](https://developer.apple.com/documentation/swift/floatingpoint/2295205-addproduct).
public mutating func addProduct(_ lhs: Failable<T, Validations>, _ rhs: Failable<T, Validations>) {
self = self.map { value in
var result = value
let _: Failable<(), EmptyValidation<()>> = try Failable.map(lhs, rhs) { left, right in
result.addProduct(left, right)
}.verified()
return result
}
}
/// See [`FloatingPoint.isEqual(to:)`](https://developer.apple.com/documentation/swift/floatingpoint/1846385-isequal).
public func isEqual(to other: Failable<T, Validations>) -> Bool {
return self == other
}
/// See [`FloatingPoint.isLess(than:)`](https://developer.apple.com/documentation/swift/floatingpoint/1849403-isless).
public func isLess(than other: Failable<T, Validations>) -> Bool {
return self < other
}
/// See [`FloatingPoint.isLessThanOrEqualTo(_:)`](https://developer.apple.com/documentation/swift/floatingpoint/1849007-islessthanorequalto).
public func isLessThanOrEqualTo(_ other: Failable<T, Validations>) -> Bool {
return self <= other
}
/// See [`FloatingPoint.isTotallyOrdered(belowOrEqualTo:)`](https://developer.apple.com/documentation/swift/floatingpoint/2428057-istotallyordered).
public func isTotallyOrdered(belowOrEqualTo other: Failable<T, MagnitudeValidation<T>>) -> Bool {
let ordered: Failable<Bool, EmptyValidation<Bool>> = Failable.map(self, other) { left, right -> Bool in
return left.isTotallyOrdered(belowOrEqualTo: right)
}
return ordered.value ?? false
}
}
extension Failable: BinaryFloatingPoint where T: BinaryFloatingPoint, Validations == MagnitudeValidation<T> {
/// See [`BinaryFloatingPoint.RawSignificand`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1846956-rawexponent).
public typealias RawSignificand = Failable<T.RawSignificand, EmptyValidation<T.RawSignificand>>
/// See [`BinaryFloatingPoint.RawExponent`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1848447-rawsignificand).
public typealias RawExponent = Failable<T.RawExponent, EmptyValidation<T.RawExponent>>
/// See [`BinaryFloatingPoint.exponentBitCount`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1847221-exponentbitcount).
public static var exponentBitCount: Int {
return T.exponentBitCount
}
/// See [`BinaryFloatingPoint.significandBitCount`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1846714-significandbitcount).
public static var significandBitCount: Int {
return T.significandBitCount
}
/// See [`BinaryFloatingPoint.significandWidth`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1847322-significandwidth).
public var significandWidth: Int {
return self.value?.significandWidth ?? 0
}
/// See [`BinaryFloatingPoint.binade`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1848292-binade).
public var binade: Failable<T, Validations> {
return self[keyPath: \.binade]
}
/// See [`BinaryFloatingPoint.exponentBitPattern`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1846505-exponentbitpattern).
public var exponentBitPattern: Failable<T.RawExponent, EmptyValidation<T.RawExponent>> {
return self[keyPath: \.exponentBitPattern]
}
/// See [`BinaryFloatingPoint.significandBitPattern`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1845838-significandbitpattern).
public var significandBitPattern: Failable<T.RawSignificand, EmptyValidation<T.RawSignificand>> {
return self[keyPath: \.significandBitPattern]
}
/// See [`BinaryFloatingPoint.init(sign:exponentBitPattern:significandBitPattern)`](https://developer.apple.com/documentation/swift/binaryfloatingpoint/1849503-init).
public init(sign: FloatingPointSign, exponentBitPattern expBP: RawExponent, significandBitPattern sigBP: RawSignificand) {
self = Failable.map(expBP, sigBP) { exp, sig in T(sign: sign, exponentBitPattern: exp, significandBitPattern: sig) }
}
}
/// See [`Numeric.*(_:_:)`](https://developer.apple.com/documentation/swift/numeric/2883821).
public func / <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Failable<T, AppendedValidations<V1, V2>>
where T: FloatingPoint
{
return Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left / right }
}
/// See [`AdditiveArithmetic.-=(_:_:)`](https://developer.apple.com/documentation/swift/additivearithmetic/3126828).
public func /= <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>) where T: FloatingPoint {
lhs = Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left / right }
}

View File

@ -0,0 +1,301 @@
extension Failable: UnsignedInteger where T: UnsignedInteger { }
extension Failable: SignedInteger where T: SignedInteger { }
extension Failable: FixedWidthInteger where T: FixedWidthInteger {
/// See [`FixedWidthInteger.bitWidth`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2886552-bitwidth).
public static var bitWidth: Int {
return T.bitWidth
}
/// See [`FixedWidthInteger.min`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884515-min).
public static var min: Failable<T, Validations> {
return Failable(T.min)
}
/// See [`FixedWidthInteger.max`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2883788-max).
public static var max: Failable<T, Validations> {
return Failable(T.max)
}
/// See [`FixedWidthInteger.nonzeroBitCount`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2885911-nonzerobitcount).
public var nonzeroBitCount: Int {
return self.value?.nonzeroBitCount ?? 0
}
/// See [`FixedWidthInteger.leadingZeroBitCount`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2883995-leadingzerobitcount).
public var leadingZeroBitCount: Int {
return self.value?.leadingZeroBitCount ?? 0
}
/// See [`FixedWidthInteger.byteSwapped`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884324-byteswapped).
public var byteSwapped: Failable<T, Validations> {
return self.map { $0.byteSwapped }
}
/// I don't know what this initializer is for. The `FixedWidthInteger` requires it,
/// but I can't find the documentation. Here's a unicorn instead: 🦄
public init<BI>(_truncatingBits truncatingBits: BI) where BI : BinaryInteger {
self = Failable(T(truncatingBits))
}
/// See [`FixedWidthInteger.addingReportingOverflow(_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2885260-addingreportingoverflow).
public func addingReportingOverflow(_ rhs: Failable<T, Validations>)
-> (partialValue: Failable<T, Validations>, overflow: Bool)
{
let result: Failable<(T, Bool), EmptyValidation<(T, Bool)>> = Failable.map(self, rhs) { left, right in
return left.addingReportingOverflow(right)
}
let overflow: Failable<Bool, EmptyValidation<Bool>> = result.map { $0.1 }
return (partialValue: result.map { $0.0 }, overflow: overflow.value ?? false)
}
/// See [`FixedWidthInteger.subtractingReportingOverflow(_:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2885098-subtractingreportingoverflow).
public func subtractingReportingOverflow(_ rhs: Failable<T, Validations>)
-> (partialValue: Failable<T, Validations>, overflow: Bool)
{
let result: Failable<(T, Bool), EmptyValidation<(T, Bool)>> = Failable.map(self, rhs) { left, right in
return left.subtractingReportingOverflow(right)
}
let overflow: Failable<Bool, EmptyValidation<Bool>> = result.map { $0.1 }
return (partialValue: result.map { $0.0 }, overflow: overflow.value ?? false)
}
/// See [`FixedWidthInteger.multipliedReportingOverflow(by:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884864-multipliedreportingoverflow).
public func multipliedReportingOverflow(by rhs: Failable<T, Validations>)
-> (partialValue: Failable<T, Validations>, overflow: Bool)
{
let result: Failable<(T, Bool), EmptyValidation<(T, Bool)>> = Failable.map(self, rhs) { left, right in
return left.multipliedReportingOverflow(by: right)
}
let overflow: Failable<Bool, EmptyValidation<Bool>> = result.map { $0.1 }
return (partialValue: result.map { $0.0 }, overflow: overflow.value ?? false)
}
/// See [`FixedWidthInteger.dividedReportingOverflow(by:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2885588-dividedreportingoverflow).
public func dividedReportingOverflow(by rhs: Failable<T, Validations>)
-> (partialValue: Failable<T, Validations>, overflow: Bool)
{
let result: Failable<(T, Bool), EmptyValidation<(T, Bool)>> = Failable.map(self, rhs) { left, right in
return left.dividedReportingOverflow(by: right)
}
let overflow: Failable<Bool, EmptyValidation<Bool>> = result.map { $0.1 }
return (partialValue: result.map { $0.0 }, overflow: overflow.value ?? false)
}
/// See [`FixedWidthInteger.remainderReportingOverflow(dividingBy:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2892758-remainderreportingoverflow).
public func remainderReportingOverflow(dividingBy rhs: Failable<T, Validations>)
-> (partialValue: Failable<T, Validations>, overflow: Bool)
{
let result: Failable<(T, Bool), EmptyValidation<(T, Bool)>> = Failable.map(self, rhs) { left, right in
return left.remainderReportingOverflow(dividingBy: right)
}
let overflow: Failable<Bool, EmptyValidation<Bool>> = result.map { $0.1 }
return (partialValue: result.map { $0.0 }, overflow: overflow.value ?? false)
}
/// See [`FixedWidthInteger.multipliedFullWidth(by:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884581-multipliedfullwidth).
public func multipliedFullWidth(by other: Failable<T, Validations>)
-> (high: Failable<T, Validations>, low: Failable<T.Magnitude, MagnitudeValidation<T.Magnitude>>)
{
let results: Failable<(T, T.Magnitude), EmptyValidation<(T, T.Magnitude)>> = Failable.map(self, other) { left, right in
return left.multipliedFullWidth(by: right)
}
return (results.map { $0.0 }, results.map { $0.1 })
}
/// See [`FixedWidthInteger.dividingFullWidth(dividend:)`](https://developer.apple.com/documentation/swift/fixedwidthinteger/2884055-dividingfullwidth).
public func dividingFullWidth(
_ dividend: (high: Failable<T, Validations>, low: Failable<T.Magnitude, MagnitudeValidation<T.Magnitude>>)
) -> (quotient: Failable<T, Validations>, remainder: Failable<T, Validations>) {
switch (self.stored, dividend.high.stored, dividend.low.stored) {
case let (.success(l), .success(high), .success(low)):
let result = l.dividingFullWidth((high, low))
return (Failable(result.quotient), Failable(result.remainder))
case let (_, .failure(left), .failure(right)):
let error = ValidationError.foundError(ErrorJoin(left, right))
return (Failable(error), Failable(error))
case (.failure(let err), _, _), (_, .failure(let err), _), (_, _, .failure(let err)):
let error = ValidationError.foundError(err)
return (Failable(error), Failable(error))
}
}
}
extension Failable: BinaryInteger where T: BinaryInteger {
/// See [`BinaryInteger.Words`](https://developer.apple.com/documentation/swift/binaryinteger/2894610-words).
public typealias Words = Array<UInt>
/// See [`BinaryInteger.bitWidth`](https://developer.apple.com/documentation/swift/binaryinteger/2886690-bitwidth).
public var bitWidth: Int {
return self.value?.bitWidth ?? 0
}
/// See [`BinaryInteger.init(_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885704-init).
public init<BI>(_ source: BI) where BI: BinaryInteger {
self = Failable(T(source))
}
/// See [`BinaryInteger.init(_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884166-init).
public init<BFP>(_ source: BFP) where BFP : BinaryFloatingPoint {
self = Failable(T(source))
}
/// See [`BinaryInteger.init(clamping:)`](https://developer.apple.com/documentation/swift/binaryinteger/2886143-init).
public init<BI>(clamping source: BI) where BI: BinaryInteger {
self = Failable(T(clamping: source))
}
/// See [`BinaryInteger.init(exactly:)`](https://developer.apple.com/documentation/swift/binaryinteger/2925955-init).
public init?<BFP>(exactly source: BFP) where BFP : BinaryFloatingPoint {
guard let value = T(exactly: source) else { return nil }
self = Failable(value)
}
/// See [`BinaryInteger.init(truncatingIfNeeded:)`](https://developer.apple.com/documentation/swift/binaryinteger/2925529-init).
public init<BI>(truncatingIfNeeded source: BI) where BI: BinaryInteger {
let t = T(truncatingIfNeeded: source)
self = Failable(t)
}
/// See [`BinaryInteger.isSigned`](https://developer.apple.com/documentation/swift/binaryinteger/2886485-issigned).
public static var isSigned: Bool {
return T.isSigned
}
/// See [`BinaryInteger.words`](https://developer.apple.com/documentation/swift/binaryinteger/2892492-words).
public var words: Words {
return (self.value?.words).map(Array<UInt>.init) ?? []
}
/// See [`BinaryInteger.trailingZeroBitCount`](https://developer.apple.com/documentation/swift/binaryinteger/2886715-trailingzerobitcount).
public var trailingZeroBitCount: Int {
return self.value?.trailingZeroBitCount ?? 0
}
/// See [`BinaryInteger.~(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884248).
public prefix static func ~ (value: Failable<T, Validations>) -> Failable<T, Validations> {
return value.map { ~$0 }
}
/// See [`BinaryInteger./(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885552).
public static func / (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs) { left, right in return left / right }
}
/// See [`BinaryInteger./=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885191).
public static func /= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs / rhs
}
/// See [`BinaryInteger.%(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885003).
public static func % (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs) { left, right in return left % right }
}
/// See [`BinaryInteger.%=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2886158).
public static func %= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs % rhs
}
/// See [`BinaryInteger.&(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017613).
public static func & (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs) { left, right in return left & right }
}
/// See [`BinaryInteger.&=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885976).
public static func &= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs & rhs
}
/// See [`BinaryInteger.|(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017645).
public static func | (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs) { left, right in return left | right }
}
/// See [`BinaryInteger.|=(_:_:)`]().
public static func |= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs | rhs
}
/// See [`BinaryInteger.^(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884669).
public static func ^ (lhs: Failable<T, Validations>, rhs: Failable<T, Validations>) -> Failable<T, Validations> {
return Failable.map(lhs, rhs) { left, right in return left ^ right }
}
/// See [`BinaryInteger.^=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017635).
public static func ^= (lhs: inout Failable<T, Validations>, rhs: Failable<T, Validations>) {
lhs = lhs ^ rhs
}
/// See [`BinaryInteger.>>=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2926011).
public static func >>= <RHS>(lhs: inout Failable<T, Validations>, rhs: RHS) where RHS : BinaryInteger {
lhs = lhs.map { $0 >> rhs }
}
/// See [`BinaryInteger.<<=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2926303).
public static func <<= <RHS>(lhs: inout Failable<T, Validations>, rhs: RHS) where RHS : BinaryInteger {
lhs = lhs.map { $0 << rhs }
}
}
/// See [`BinaryInteger.%(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885003).
public func % <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Failable<T, AppendedValidations<V1, V2>>
where T: BinaryInteger
{
return Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left % right }
}
/// See [`BinaryInteger.&(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017613).
public func & <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Failable<T, AppendedValidations<V1, V2>>
where T: BinaryInteger
{
return Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left & right }
}
/// See [`BinaryInteger.<(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885984).
public func < <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Bool
where T: BinaryInteger
{
return Failable<Bool, EmptyValidation<Bool>>(Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> Bool in left < right }).value ?? false
}
/// See [`BinaryInteger.^(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017635).
public func ^ <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Failable<T, AppendedValidations<V1, V2>>
where T: BinaryInteger
{
return Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left ^ right }
}
/// See [`BinaryInteger.|(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/3017645).
public func | <T, V1, V2>(lhs: Failable<T, V1>, rhs: Failable<T, V2>) -> Failable<T, AppendedValidations<V1, V2>>
where T: BinaryInteger
{
return Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left | right }
}
/// See [`BinaryInteger.%=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2886158).
public func %= <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>) where T: BinaryInteger {
lhs = Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left % right }
}
/// See [`BinaryInteger.&=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885976).
public func &= <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>) where T: BinaryInteger {
lhs = Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left & right }
}
/// See [`BinaryInteger.^=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2885182).
public func ^= <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>) where T: BinaryInteger {
lhs = Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left ^ right }
}
/// See [`BinaryInteger.|=(_:_:)`](https://developer.apple.com/documentation/swift/binaryinteger/2884669).
public func |= <T, V1, V2>(lhs: inout Failable<T, V1>, rhs: Failable<T, V2>) where T: BinaryInteger {
lhs = Failable<T, V1>.map(lhs, rhs) { (left: T, right: T) -> T in left | right }
}

View File

@ -0,0 +1,31 @@
extension Failable: SIMDStorage where T: SIMDStorage {
/// See [`SIMDStorage.Scalar`](https://developer.apple.com/documentation/swift/simdstorage/3140578-scalar)
public typealias Scalar = Failable<T.Scalar, EmptyValidation<T.Scalar>>
/// See [`SIMDStorage.scalarCount`](https://developer.apple.com/documentation/swift/simdstorage/3140580-scalarcount)
public var scalarCount: Int {
return self.value?.scalarCount ?? 0
}
/// See [`SIMDStorage.init()`](https://developer.apple.com/documentation/swift/simdstorage/3140579-init).
public init() {
self = Failable(T())
}
/// See [`subscript(_:)`](https://developer.apple.com/documentation/swift/simdstorage/3140581-subscript).
public subscript(index: Int) -> Scalar {
get {
return self.map { vectors in vectors[index] }
}
set {
if let value = newValue.value {
self.value?[index] = value
}
}
}
}
extension Failable: SIMD where T: SIMD {
/// See [`SIMD.MaskStorage`](https://developer.apple.com/documentation/swift/simd/3139486-maskstorage).
public typealias MaskStorage = T.MaskStorage
}

View File

@ -1,3 +1,6 @@
/// A `Failable` type with a validation that can't fail.
public typealias NonFailable<T> = Failable<T, EmptyValidation<T>>
/// A type that can fail when being set because the new value does pass certain validations.
///
/// You can create a `Failable` instance in 2 ways. The first is to use the `Failable` initializer:
@ -27,33 +30,200 @@
/// `Failable` supprts initialization with certain type literals if the `value` type `T` also supports it.
/// Initialization is supported for `Int`, `Float`, `Bool`, `nil`, and `String` types.
///
/// let string = Failable<String, EmptyValidationM<String>> = "Hello world"
/// let string = Failable<String, EmptyValidation<String>> = "Hello world"
///
/// - Warning: Because literal initializers cannot fail, your program will crash if the value passed in does not pass validation.
///
/// `Dictionary` and `Array` types are not supported for literal initialization yet because array
/// splatting for variadic parameters is not supported yet.
public struct Failable<T, Validations> where Validations: Validation, Validations.Supported == T {
/// The underlaying value that has been validated.
internal private(set) var stored: Result<T, Error>
init(result: Result<T, Error>) {
self.stored = result
}
init(_ error: Error) {
self.stored = .failure(error)
}
/// Gets the stored value of the current instance if it exists.
///
/// - Note: The setter for this property is not public.
public internal(set) var value: T
/// Thie property will return `nil` if an error is held instead.
///
/// You can set the stored value if the `Failable` instance by using this properties setter.
/// The value will not be set if `T` is non-optional and `nil` is passed in.
public var value: T? {
get {
guard case let .success(value) = self.stored else { return nil }
return value
}
set {
if newValue == nil, !_isOptional(T.self) { return }
guard let value = newValue else { return }
self.stored = Result(catching: {
try Validations.run(value)
return value
})
}
}
/// Gets the error stored in the current instance.
///
/// This property returns `nil` if a value of type `T` is stored instead.
public var error: Error? {
guard case let .failure(error) = self.stored else { return nil }
return error
}
/// Creates a new `Failable` instance.
///
/// - Parameter t: The orginal value for the instance.
/// This value will be validated and the initializer will fail if it doesn't pass.
public init(_ t: T)throws {
try Validations.run(t)
self.value = t
public init(_ t: T) {
self.stored = Result.init(catching: {
try Validations.run(t)
return t
})
}
/// Gets the value of a property of the `value` property using a key path.
/// Creates a new `Failable` instance.
///
/// - Parameter path: The key path of the property to get from the `value` property.
public subscript<Value>(keyPath path: KeyPath<T, Value>) -> Value {
return self.value[keyPath: path]
/// - Parameters:
/// - t: The initial value for the instance.
/// - validation: The validation type for the instance.
public init(_ t: T, _ validation: Validations.Type) {
self.init(t)
}
/// Initialize a new `Failable` instance from an already existing instance.
/// This can be useful to specify the types of an ambiguous `Failable` instance.
///
/// - Parameter failable: The `Failable` instance to initialize with.
public init(_ failable: Failable<T, Validations>) {
self = failable
}
/// Gets the value stored in the current instance.
///
/// - Returns: The stored value, of type `T`.
/// - Throws: The error stored in the current value.
public func get()throws -> T {
return try self.stored.get()
}
/// Verified that the current instance contains a value instead of an error.
/// If an error is found, it will be thrown.
///
/// - Returns: Self, if it contains a value value.
/// - Throws: The stored `Error` instance.
public func verified()throws -> Failable<T, Validations> {
switch self.stored {
case let .failure(error): throw error
case .success: return self
}
}
/// Converts the stored value to another value of a different type, which will be the stored value of a new
/// `Failable` instance with a different `Validation` type.
///
/// - Parameters:
/// - transform: The mapping closure that transforms the stored value.
/// - value: The stored value of the current instance that will be converted.
///
/// - Returns: A new `Failable` instance that uses the value returned by the `transform` closure.
public func map<Value, NewValidations>(_ transform: (_ value: T)throws -> Value) -> Failable<Value, NewValidations> {
switch self.stored {
case let .success(value): return Failable<Value, NewValidations>(result: Result(catching: { try transform(value) }))
case let .failure(error): return Failable<Value, NewValidations>(result: .failure(error))
}
}
/// Converts the stored value to another value of the same type with the same validations.
///
/// - Parameters:
/// - transform: The mapping function to convert the stored value.
/// - value: The stored value of the current instance to convert.
///
/// - Returns: A new `Failable` instance with value returned by the `transform` closure.
public func map(_ transform: (_ value: T)throws -> T) -> Failable<T, Validations> {
switch self.stored {
case let .success(value): return Failable(result: Result(catching: { try transform(value) }))
case let .failure(error): return Failable(result: .failure(error))
}
}
/// Converts the stored value to a `Failable` instance that contains a value of a different type and that uses
/// a different `Validation` type.
///
/// - Parameters:
/// - transform: The mapping closure that converts the stored value to a `Failable` instance.
/// - value: The stored value of the current instance that will be converted.
///
/// - Returns: The `Failable` instance that was returned from the `trasnform` closure.
public func flatMap<Value, NewValidations>(
_ transform: (T)throws -> Failable<Value, NewValidations>
) -> Failable<Value, NewValidations> {
switch self.stored {
case let .success(t):
do {
return try transform(t)
} catch let error {
return Failable<Value, NewValidations>(result: .failure(error))
}
case let .failure(error): return Failable<Value, NewValidations>(result: .failure(error))
}
}
/// Converts the stored value to a `Failable` instance with matching `T` and `Validations` types.
///
/// - Parameters:
/// - transform: The mapping closure that convert the stored value to a `Failable` instance.
/// - value: The stored value of the current instance that will be converted.
///
/// - Returns: The `Failable` instance that was returned from the `trasnform` closure.
public func flatMap(_ transform: (_ value: T)throws -> Failable<T, Validations>) -> Failable<T, Validations> {
switch self.stored {
case let .success(value):
do {
return try transform(value)
} catch let error {
return Failable(result: .failure(error))
}
case let .failure(error): return Failable(result: .failure(error))
}
}
/// Accesses the value of a keypath for the stored value where the stored value type
/// and the keypath value type are equivalent.
///
/// - Parameter path: The keypath of the value to access.
/// - Returns: A `Failable` instance with the value of the keypath.
public subscript (keyPath path: KeyPath<T, T>) -> Failable<T, Validations> {
return self.map { value in value[keyPath: path] }
}
/// Accesses the value of a keypath for the stored value where the stored value type and keypath value type are different.
///
/// - Parameter path: The keypath of the value to access.
/// - Returns: A `Failable` instance with the value of the keypath.
public subscript <Value, NewValidations>(keyPath path: KeyPath<T, Value>) -> Failable<Value, NewValidations> {
return self.map { value in value[keyPath: path] }
}
}
extension Failable {
public static func map<A, B, R, AV, BV, RV>(
_ left: Failable<A, AV>,
_ right: Failable<B, BV>,
closure: (A, B)throws -> R
) -> Failable<R, RV> {
switch (left.stored, right.stored) {
case let (.success(l), .success(r)): return Failable<R, RV>(result: Result(catching: { try closure(l, r) }))
case let (.failure(l), .failure(r)): return Failable<R, RV>(ValidationError.foundError(ErrorJoin(l, r)))
case let (.success, .failure(error)): return Failable<R, RV>(ValidationError.foundError(error))
case let (.failure(error), .success): return Failable<R, RV>(ValidationError.foundError(error))
}
}
}
@ -66,7 +236,7 @@ extension CustomStringConvertible {
/// var story: Failable<String, Length1028> = try "Once upon a time...".failable()
///
/// - Parameter validations: The validation type to use when mutating the stored value.
public func failable<Validations>(_ validations: Validations.Type = Validations.self)throws -> Failable<Self, Validations> {
return try Failable(self)
public func failable<Validations>(_ validations: Validations.Type = Validations.self) -> Failable<Self, Validations> {
return Failable(self)
}
}

View File

@ -10,7 +10,6 @@ infix operator <~: AssignmentPrecedence
/// - Parameters:
/// - root: The `Failable` instance that holds the value to be mutated.
/// - value: The new value for the `root.value` property.
public func <~ <T, Validations>(root: inout Failable<T, Validations>, value: T)throws {
try Validations.run(value)
public func <~ <T, Validations>(root: inout Failable<T, Validations>, value: T) {
root.value = value
}

View File

@ -0,0 +1,66 @@
extension Optional: ExpressibleByIntegerLiteral where Wrapped: ExpressibleByIntegerLiteral {
/// See [`ExpressibleByIntegerLiteral.init(integerLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyintegerliteral/2298913-init).
public init(integerLiteral value: Wrapped.IntegerLiteralType) {
self = Optional<Wrapped>.some(Wrapped(integerLiteral: value))
}
}
extension Optional: ExpressibleByFloatLiteral where Wrapped: ExpressibleByFloatLiteral {
/// See [`ExpressibleByFloatLiteral.init(floatLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyfloatliteral/2294405-init).
public init(floatLiteral value: Wrapped.FloatLiteralType) {
self = Optional<Wrapped>.some(Wrapped(floatLiteral: value))
}
}
extension Optional: ExpressibleByBooleanLiteral where Wrapped: ExpressibleByBooleanLiteral {
/// See [`ExpressibleByBooleanLiteral.init(booleanLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebybooleanliteral/2296011-init).
public init(booleanLiteral value: Wrapped.BooleanLiteralType) {
self = Optional<Wrapped>.some(Wrapped(booleanLiteral: value))
}
}
extension Optional: ExpressibleByStringLiteral where Wrapped: ExpressibleByStringLiteral {
/// See [`ExpressibleByStringLiteral.init(stringLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebystringliteral/2294174-init)
public init(stringLiteral value: Wrapped.StringLiteralType) {
self = Optional<Wrapped>.some(Wrapped(stringLiteral: value))
}
}
extension Optional: ExpressibleByExtendedGraphemeClusterLiteral
where Wrapped: ExpressibleByExtendedGraphemeClusterLiteral
{
/// See [`ExpressibleByExtendedGraphemeClusterLiteral.init(extendedGraphemeClusterLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyextendedgraphemeclusterliteral/2294280-init).
public init(extendedGraphemeClusterLiteral value: Wrapped.ExtendedGraphemeClusterLiteralType) {
self = Optional<Wrapped>.some(Wrapped(extendedGraphemeClusterLiteral: value))
}
}
extension Optional: ExpressibleByUnicodeScalarLiteral where Wrapped: ExpressibleByUnicodeScalarLiteral {
/// See [`ExpressibleByUnicodeScalarLiteral.init(unicodeScalarLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyunicodescalarliteral/2296043-init).
public init(unicodeScalarLiteral value: Wrapped.UnicodeScalarLiteralType) {
self = Optional<Wrapped>.some(Wrapped(unicodeScalarLiteral: value))
}
}
extension Optional: ExpressibleByArrayLiteral where Wrapped: ExpressibleByArrayLiteral {
/// See [`ExpressibleByArrayLiteral.init(arrayLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebyarrayliteral/2908652-init).
public init(arrayLiteral elements: Wrapped.ArrayLiteralElement...) {
let initializer = unsafeBitCast(
Wrapped.init(arrayLiteral:),
to: (([Wrapped.ArrayLiteralElement]) -> Wrapped).self
)
self = Optional<Wrapped>.some(initializer(elements))
}
}
extension Optional: ExpressibleByDictionaryLiteral where Wrapped: ExpressibleByDictionaryLiteral {
/// See [`ExpressibleByDictionaryLiteral.init(dictionaryLiteral:)`](https://developer.apple.com/documentation/swift/expressiblebydictionaryliteral/2295781-init).
public init(dictionaryLiteral elements: (Wrapped.Key, Wrapped.Value)...) {
let initializer = unsafeBitCast(
Wrapped.init(dictionaryLiteral:),
to: (([(Wrapped.Key, Wrapped.Value)]) -> Wrapped).self
)
self = Optional(initializer(elements))
}
}

View File

@ -3,10 +3,10 @@
/// This validation is used for things such as numeric operations where `Failable` types with different validations are used.
///
/// The validations used must have the same `Supported` type.
public struct AppendedValidations<T, V1, V2>: Validation where V1: Validation, V2: Validation, V1.Supported == T, V2.Supported == T {
public struct AppendedValidations<V1, V2>: Validation where V1: Validation, V2: Validation, V1.Supported == V2.Supported {
/// See `Validation.Supported`.
public typealias Supported = T
public typealias Supported = V1.Supported
/// See `Validation.subvalidations`.
///

View File

@ -0,0 +1,6 @@
/// A `Validation` implementation that supports any type and always succeedes.
public struct EmptyValidation<T>: Validation {
/// See `Validation.validate(_:)`.
public static func validate(_ value: T)throws { }
}

View File

@ -3,29 +3,29 @@ import XCTest
final class FailableTests: XCTestCase {
func testInit()throws {
var story: Failable<String, EmptyValidation<String>> = try "Hello world...".failable()
var story: NonFailable<String> = "Hello world...".failable()
XCTAssertEqual(story.value, "Hello world...")
story = try "Long long ago...".failable()
story = "Long long ago...".failable()
XCTAssertEqual(story.value, "Long long ago...")
}
func testSet()throws {
var story: Failable<String, EmptyValidation<String>> = try "Hello world...".failable()
try story <~ "Long long ago..."
var story: NonFailable<String> = "Hello world...".failable()
story <~ "Long long ago..."
XCTAssertEqual(story.value, "Long long ago...")
}
func testKeyPathSubscript()throws {
let string = "Hello World"
let failable: Failable<String, EmptyValidation<String>> = try string.failable()
let failable: NonFailable<String> = string.failable()
XCTAssertEqual(failable[keyPath: \.count], string.count)
}
func testEncode()throws {
let data: Failable<[String: String], EmptyValidation<[String: String]>> = try ["key": "value"].failable()
let data = Failable(["key": "value"], EmptyValidation<[String: String]>.self)
let json = try String(data: JSONEncoder().encode(data), encoding: .utf8)
XCTAssertEqual(json, "{\"key\":\"value\"}")
@ -37,7 +37,7 @@ final class FailableTests: XCTestCase {
"key": "value"
}
""".data(using: .utf8)!
let object = try JSONDecoder().decode(Failable<[String: String], EmptyValidation<[String: String]>>.self, from: json)
let object = try JSONDecoder().decode(NonFailable<[String: String]>.self, from: json)
XCTAssertEqual(object.value, ["key": "value"])
}

View File

@ -17,29 +17,32 @@ internal typealias StringLengthArray = ElementValidation<[String], Length1028<St
final class CollectionTests: XCTestCase {
func testLengthValidation()throws {
try XCTAssertThrowsError(Failable<[Bool], LengthRange10To1028<[Bool]>>([]))
try XCTAssertThrowsError(Failable([], LengthRange10To1028<[Bool]>.self).get())
var bools = try Failable<[Bool], LengthRange10To1028<[Bool]>>([true, true, true, false, false, false, true, true, false, false])
var bools = Failable([true, true, true, false, false, false, true, true, false, false], LengthRange10To1028<[Bool]>.self)
XCTAssertEqual(bools.value, [true, true, true, false, false, false, true, true, false, false])
try XCTAssertThrowsError(bools <~ Array(repeating: true, count: 5))
try XCTAssertThrowsError(bools <~ Array(repeating: false, count: 5))
try XCTAssertThrowsError(bools <~ Array(repeating: true, count: 1029))
try XCTAssertThrowsError(bools <~ Array(repeating: false, count: 1029))
bools <~ Array(repeating: true, count: 5)
bools <~ Array(repeating: false, count: 5)
bools <~ Array(repeating: true, count: 1029)
bools <~ Array(repeating: false, count: 1029)
try XCTAssertThrowsError(bools.get())
let array = Array(repeating: true, count: 1028)
try bools <~ array
bools <~ array
XCTAssertEqual(bools.value, array)
}
func testElementValidation()throws {
let tooLong = String(repeating: "x", count: 1029)
let longest = String(repeating: "g", count: 1028)
var strings = try Failable<[String], StringLengthArray>(["G", "D", "A", "E"])
var strings = Failable<[String], StringLengthArray>(["G", "D", "A", "E"])
XCTAssertEqual(strings.value, ["G", "D", "A", "E"])
try XCTAssertThrowsError(strings <~ ["G", "O", "O", tooLong])
try strings <~ ["G", "OOOO", "World", longest]
strings <~ ["G", "O", "O", tooLong]
try XCTAssertThrowsError(strings.get())
strings <~ ["G", "OOOO", "World", longest]
XCTAssertEqual(strings.value, ["G", "OOOO", "World", longest])
}
}

View File

@ -24,34 +24,40 @@ final class ComparableTests: XCTestCase {
func testNumberThousand()throws {
var int = Failable<Int, NumberThousand>(5_000)
try int <~ 9_999
try int <~ 1_000
int <~ 9_999
int <~ 1_000
try XCTAssertNoThrow(int.get())
try XCTAssertThrowsError(int <~ 999)
try XCTAssertThrowsError(int <~ 10_000)
int <~ 999
int <~ 10_000
try XCTAssertThrowsError(int.get())
}
func testGreaterThan()throws {
var int = Failable<Int, GreaterThan>(5_000)
try int <~ 1_000
try int <~ 10_000
try int <~ Int.max
int <~ 1_000
int <~ 10_000
int <~ Int.max
try XCTAssertNoThrow(int.get())
try XCTAssertThrowsError(int <~ 999)
try XCTAssertThrowsError(int <~ 0)
try XCTAssertThrowsError(int <~ Int.min)
int <~ 999
int <~ 0
int <~ Int.min
try XCTAssertThrowsError(int.get())
}
func testLessThan()throws {
var int = Failable<Int, LessThan>(5_000)
try int <~ 9_999
try int <~ 999
try int <~ 0
try int <~ Int.min
int <~ 9_999
int <~ 999
int <~ 0
int <~ Int.min
try XCTAssertNoThrow(int.get())
try XCTAssertThrowsError(int <~ 10_000)
try XCTAssertThrowsError(int <~ Int.max)
int <~ 10_000
int <~ Int.max
try XCTAssertThrowsError(int.get())
}
}

View File

@ -5,24 +5,28 @@ typealias OptionalStringLength = NotNilValidate<LengthRange10To1028<String>>
final class OptionalTests: XCTestCase {
func testNotNil()throws {
var optional = try Failable<Bool?, NotNil<Bool>>.init(false)
var optional: Failable<Bool?, NotNil<Bool>> = false
try optional <~ true
try optional <~ false
optional <~ true
optional <~ false
try XCTAssertNoThrow(optional.get())
try XCTAssertThrowsError(optional <~ nil)
optional <~ nil
try XCTAssertThrowsError(optional.get())
}
func testNotNilValidate()throws {
var optional = try Failable<String?, OptionalStringLength>.init("Hello World")
var optional: Failable<String?, OptionalStringLength> = "Hello World"
try optional <~ "Long long ago"
try optional <~ String(repeating: "x", count: 10)
try optional <~ String(repeating: "x", count: 1028)
try optional <~ nil
optional <~ "Long long ago"
optional <~ String(repeating: "x", count: 10)
optional <~ String(repeating: "x", count: 1028)
optional <~ nil
try XCTAssertNoThrow(optional.get())
try XCTAssertThrowsError(optional <~ String(repeating: "x", count: 9))
try XCTAssertThrowsError(optional <~ String(repeating: "x", count: 1029))
optional <~ String(repeating: "x", count: 9)
optional <~ String(repeating: "x", count: 1029)
try XCTAssertThrowsError(optional.get())
}
}

View File

@ -7,16 +7,18 @@ internal struct USPhoneNumber: RegexValidation {
final class StringTests: XCTestCase {
func testUSPhoneNumber()throws {
var number: Failable<String, USPhoneNumber> = try "731-943-4316".failable()
var number: Failable<String, USPhoneNumber> = "731-943-4316".failable()
try number <~ "(731)-943-4316"
try number <~ "1-731-943-4316"
try number <~ "7319434316"
number <~ "(731)-943-4316"
number <~ "1-731-943-4316"
number <~ "7319434316"
try XCTAssertNoThrow(number.get())
try XCTAssertThrowsError(number <~ "")
try XCTAssertThrowsError(number <~ "943-4316")
try XCTAssertThrowsError(number <~ "1-800-EAT-MEAT")
try XCTAssertThrowsError(number <~ "4316-943-731")
number <~ ""
number <~ "943-4316"
number <~ "1-800-EAT-MEAT"
number <~ "4316-943-731"
try XCTAssertThrowsError(number.get())
}
}