File: LengthFormatter.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (214 lines) | stat: -rw-r--r-- 10,795 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//

extension LengthFormatter {
    public enum Unit: Int, Sendable {
        case millimeter = 8
        case centimeter = 9
        case meter = 11
        case kilometer = 14
        case inch = 1281
        case foot = 1282
        case yard = 1283
        case mile = 1284
    }
}

@available(*, unavailable)
extension LengthFormatter : @unchecked Sendable { }

open class LengthFormatter : Formatter {
    
    public override init() {
        numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        unitStyle = .medium
        isForPersonHeightUse = false
        super.init()
    }
    
    public required init?(coder: NSCoder) {
        numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        unitStyle = .medium
        isForPersonHeightUse = false
        super.init(coder:coder)
    }
    
    /*@NSCopying*/ open var numberFormatter: NumberFormatter! // default is NumberFormatter with NumberFormatter.Style.decimal
    open var unitStyle: UnitStyle // default is NSFormattingUnitStyleMedium
    
    open var isForPersonHeightUse: Bool // default is NO; if it is set to YES, the number argument for -stringFromMeters: and -unitStringFromMeters: is considered as a person's height
    
    // Format a combination of a number and an unit to a localized string.
    open func string(fromValue value: Double, unit: LengthFormatter.Unit) -> String {
        guard let formattedValue = numberFormatter.string(from:NSNumber(value: value)) else {
            fatalError("Cannot format \(value) as string")
        }
        let separator = unitStyle == .short ? "" : " "
        return "\(formattedValue)\(separator)\(unitString(fromValue: value, unit: unit))"
    }
    
    // Format a number in meters to a localized string with the locale-appropriate unit and an appropriate scale (e.g. 4.3m = 14.1ft in the US locale).
    open func string(fromMeters numberInMeters: Double) -> String {
        let unitLength: [Unit:UnitLength] = [.millimeter:.millimeters,
                                                     .centimeter:.centimeters,
                                                     .meter:.meters,
                                                     .kilometer:.kilometers,
                                                     .inch:.inches,
                                                     .foot:.feet,
                                                     .yard:.yards,
                                                     .mile:.miles]
        
        //Convert to the locale-appropriate unit
        let unitFromMeters = unit(fromMeters: numberInMeters)
        
        //Map the unit to UnitLength type for conversion later
        let unitLengthFromMeters = unitLength[unitFromMeters]!
        
        //Create a measurement object based on the value in meters
        let meterMeasurement = Measurement<UnitLength>(value:numberInMeters, unit: .meters)
        
        //Convert the object to the locale-appropriate unit determined above
        let unitMeasurement = meterMeasurement.converted(to: unitLengthFromMeters)
        
        //Extract the number from the measurement
        let numberInUnit = unitMeasurement.value
        
        if isForPersonHeightUse && !numberFormatter.locale.usesMetricSystem {
            let feet = numberInUnit.rounded(.towardZero)
            let feetString = string(fromValue: feet, unit: .foot)
            
            let inches = abs(numberInUnit.truncatingRemainder(dividingBy: 1.0)) * 12
            let inchesString = string(fromValue: inches, unit: .inch)
            
            return ("\(feetString), \(inchesString)")
        }
        return string(fromValue: numberInUnit, unit: unitFromMeters)
    }
    
    // Return a localized string of the given unit, and if the unit is singular or plural is based on the given number.
    open func unitString(fromValue value: Double, unit: Unit) -> String {
        if unitStyle == .short {
            return LengthFormatter.shortSymbol[unit]!
        } else if unitStyle == .medium {
            return LengthFormatter.mediumSymbol[unit]!
        } else if value == 1.0 {
            return LengthFormatter.largeSingularSymbol[unit]!
        } else {
            return LengthFormatter.largePluralSymbol[unit]!
        }
    }
    
    // Return the locale-appropriate unit, the same unit used by -stringFromMeters:.
    open func unitString(fromMeters numberInMeters: Double, usedUnit unitp: UnsafeMutablePointer<Unit>?) -> String {
        let unitLength: [Unit:UnitLength] = [.millimeter:.millimeters,
                                                     .centimeter:.centimeters,
                                                     .meter:.meters,
                                                     .kilometer:.kilometers,
                                                     .inch:.inches,
                                                     .foot:.feet,
                                                     .yard:.yards,
                                                     .mile:.miles]
        
        //Convert to the locale-appropriate unit
        let unitFromMeters = unit(fromMeters: numberInMeters)
        unitp?.pointee = unitFromMeters
        
        //Map the unit to UnitLength type for conversion later
        let unitLengthFromMeters = unitLength[unitFromMeters]!
        
        //Create a measurement object based on the value in meters
        let meterMeasurement = Measurement<UnitLength>(value:numberInMeters, unit: .meters)
        
        //Convert the object to the locale-appropriate unit determined above
        let unitMeasurement = meterMeasurement.converted(to: unitLengthFromMeters)
        
        //Extract the number from the measurement
        let numberInUnit = unitMeasurement.value
        
        //Return the appropriate representation of the unit based on the selected unit style
        return unitString(fromValue: numberInUnit, unit: unitFromMeters)
    }
    
    /// This method selects the appropriate unit based on the formatter’s locale,
    /// the magnitude of the value, and isForPersonHeightUse property.
    ///
    /// - Parameter numberInMeters: the magnitude in terms of meters
    /// - Returns: Returns the appropriate unit
    private func unit(fromMeters numberInMeters: Double) -> Unit {
        if numberFormatter.locale.usesMetricSystem {
            //Person height is always returned in cm for metric system
            if isForPersonHeightUse { return .centimeter }
            
            if numberInMeters > 1000 || numberInMeters < 0.0 {
                return .kilometer
            } else if numberInMeters > 1.0 {
                return .meter
            } else if numberInMeters > 0.01 {
                return .centimeter
            } else { return .millimeter }
        } else {
            //Person height is always returned in ft for U.S. system
            if isForPersonHeightUse { return .foot }
            
            let metricMeasurement = Measurement<UnitLength>(value:numberInMeters, unit: .meters)
            let usMeasurement = metricMeasurement.converted(to: .feet)
            let numberInFeet = usMeasurement.value
            
            if numberInFeet < 0.0 || numberInFeet > 5280 {
                return .mile
            } else if numberInFeet > 3 || numberInFeet == 0.0 {
                return .yard
            } else if numberInFeet >= 1.0 {
                return .foot
            } else { return .inch }
        }
    }
    
    /// Maps a unit to its short symbol. Reuses strings from UnitLength wherever possible.
    private static let shortSymbol: [Unit: String] = [.millimeter:UnitLength.millimeters.symbol,
                                                   .centimeter:UnitLength.centimeters.symbol,
                                                   .meter:UnitLength.meters.symbol,
                                                   .kilometer:UnitLength.kilometers.symbol,
                                                   .inch:"″",
                                                   .foot:"′",
                                                   .yard:UnitLength.yards.symbol,
                                                   .mile:UnitLength.miles.symbol]
    
    /// Maps a unit to its medium symbol. Reuses strings from UnitLength.
    private static let mediumSymbol: [Unit: String] = [.millimeter:UnitLength.millimeters.symbol,
                                                    .centimeter:UnitLength.centimeters.symbol,
                                                    .meter:UnitLength.meters.symbol,
                                                    .kilometer:UnitLength.kilometers.symbol,
                                                    .inch:UnitLength.inches.symbol,
                                                    .foot:UnitLength.feet.symbol,
                                                    .yard:UnitLength.yards.symbol,
                                                    .mile:UnitLength.miles.symbol]
    
    /// Maps a unit to its large, singular symbol.
    private static let largeSingularSymbol: [Unit: String] = [.millimeter:"millimeter",
                                                           .centimeter:"centimeter",
                                                           .meter:"meter",
                                                           .kilometer:"kilometer",
                                                           .inch:"inch",
                                                           .foot:"foot",
                                                           .yard:"yard",
                                                           .mile:"mile"]
    
    /// Maps a unit to its large, plural symbol.
    private static let largePluralSymbol: [Unit: String] = [.millimeter:"millimeters",
                                                         .centimeter:"centimeters",
                                                         .meter:"meters",
                                                         .kilometer:"kilometers",
                                                         .inch:"inches",
                                                         .foot:"feet",
                                                         .yard:"yards",
                                                         .mile:"miles"]
}