-
Notifications
You must be signed in to change notification settings - Fork 14
/
DecimalNumberCoding.swift
46 lines (37 loc) · 1.18 KB
/
DecimalNumberCoding.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//
// DecimalNumberCoding.swift
// Hollow
//
// Created by Condy on 2024/5/20.
//
import Foundation
/// `@DecimalNumberCoding` decoding the `String`、`Double`、`Float`、`CGFloat`、`Int` or `Int64` to a NSDecimalNumber property.
public struct DecimalNumberValue: Transformer {
let decimalString: String
public typealias DecodeType = NSDecimalNumber
public typealias EncodeType = String
public init?(value: Any) {
guard let string = Hollow.transfer2String(with: value), !string.hc.isEmpty2 else {
return nil
}
self.decimalString = string
}
public func transform() throws -> NSDecimalNumber? {
guard decimalString.hc.isValidDecimal else {
return nil
}
let decimal = NSDecimalNumber(string: decimalString)
if decimal.isEqual(to: NSDecimalNumber.notANumber) {
return nil
}
return decimal
}
public static func transform(from value: NSDecimalNumber) throws -> String {
value.description
}
}
extension DecimalNumberValue: DefaultValueProvider {
public static var hasDefaultValue: NSDecimalNumber {
.zero
}
}