swift Swift 3.0中的测量和单位示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 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
}

以上是关于swift Swift 3.0中的测量和单位示例的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 中测量经过的时间

在 Xcode 8 和 Swift 3.0 中删除覆盖后准备 segue 崩溃

今日扩展 Swift 3.0 中的 App Group

swift 3.0中的UITableView错误

JSON图像解析IOS Swift 3.0

swift 3.0中的uibutton问题