this repo has no description
at main 64 lines 1.8 kB view raw
1// 2// IntCodingKey.swift 3// URLQueryItemCoder 4// 5// Created by Kyle Hughes on 1/13/23. 6// 7 8/// A basic coding key implementation for integer-indexed collections. 9internal struct IntCodingKey { 10 /// The value to use in an integer-indexed collection (e.g. an int-keyed dictionary). 11 internal let intValue: Int? 12 13 /// The string to use in a named collection (e.g. a string-keyed dictionary). 14 internal let stringValue: String 15 16 // MARK: Private Initialization 17 18 private init(intValue: Int?, stringValue: String) { 19 self.intValue = intValue 20 self.stringValue = stringValue 21 } 22} 23 24// MARK: - CodingKey Extension 25 26extension IntCodingKey: CodingKey { 27 // MARK: Internal Initialization 28 29 /// Creates a new instance from the specified integer. 30 /// 31 /// - Parameter intValue: The integer value of the desired key. 32 internal init(intValue: Int) { 33 self.intValue = intValue 34 35 stringValue = String(intValue) 36 } 37 38 /// Creates a new instance from the given string, converted to an integer. 39 /// 40 /// - Parameter stringValue: The string value of the desired key. 41 /// - Returns: The instance, or `nil` if the string couldn't be converted. 42 internal init?(stringValue: String) { 43 guard let intValue = Int(stringValue) else { 44 return nil 45 } 46 47 self.intValue = intValue 48 self.stringValue = stringValue 49 } 50} 51 52// MARK: - ExpressibleByIntegerLiteral Extension 53 54extension IntCodingKey: ExpressibleByIntegerLiteral { 55 // MARK: Internal Initialization 56 57 /// Creates an instance initialized to the given integer value. 58 /// 59 /// - Parameter integerLiteral: The value of the new instance. 60 @inlinable 61 internal init(integerLiteral value: Int) { 62 self.init(intValue: value) 63 } 64}