ahcode0919
4/17/2017 - 10:48 PM

Example of Measurements and Units in Swift 3.0

Example of Measurements and Units in Swift 3.0



extension String {
    func getDecimalDigits(includeDecimal: Bool = true) -> String {
        let set = includeDecimal ? "1234567890.": "1234567890"
        return self.components(separatedBy: CharacterSet(charactersIn: set).inverted).joined()
    }
    
    func lettersOnly() -> String {
        let characterSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").inverted
        return self.components(separatedBy: characterSet).joined()
    }
}

extension UnitLength {
    private static let imperialUnitLengths: [UnitLength] = [.inches, .feet, .miles]
    var isMetric: Bool {
        return !UnitLength.imperialUnitLengths.contains(self)
    }
}

func getUnitLength(from measurement: String) -> UnitLength? {
    let formattedString = measurement.lettersOnly().lowercased()
    
    //We are assuming that the input has been pre-processed and only contains the measurement unit
    //with or without decimal digits.
    switch formattedString {
    case "mm", "millimeter", "millimeters":
        return UnitLength.millimeters
    case "cm", "centimeter", "centimeters":
        return UnitLength.centimeters
    case "m", "meter", "meters":
        return UnitLength.meters
    case "km", "kilometer", "kilometers":
        return UnitLength.kilometers
    case "in", "inch", "inches":
        return UnitLength.inches
    case "ft", "feet", "foot":
        return UnitLength.feet
    case "mi", "mile", "miles":
        return UnitLength.miles
    default:
        return nil
    }
}


func getMeasurement(from measurementString: String) -> Measurement<UnitLength>? {
    guard let double = Double(measurementString.getDecimalDigits()),
        let unit = getUnitLength(from: measurementString) else {
        return nil
    }
    return Measurement(value: double, unit: unit)
}

if let measurement = getMeasurement(from: "5.2 miles"),
    let measurement2 = getMeasurement(from: "6.45 miles") {
    assert(measurement < measurement2) //true
}