我可以在 Swift 闭包中使用多个分隔符拆分数字字符串吗? [英] can I split a numeric string using multiple separators in a Swift closure?

查看:44
本文介绍了我可以在 Swift 闭包中使用多个分隔符拆分数字字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含小数和十进制数的字符串数组.

I have a string array with fractional numbers and decimal numbers.

    let stringArray = [ "0.0", "193.16", "5/4", "503.42", "696.58", "25/16", "1082.89", "2/1"]

每个数组元素都映射到一个闭包中,从字符串中提取数字.

Each array element is mapped in a closure where numbers are extracted from the string.

    let values = stringArray.map { s -> Double in

小数部分(参见之前的帖子)

    let splitStrings = s.characters.split(separator: "/").map(String.init).map({ Double($0) })

或十进制

    let splitStrings = s.characters.split(separator: ".").map(String.init).map({ Double($0) })

问题:在 Swift 中,有没有一种方法可以使用多个分隔符来拆分字符串,以便单个闭包可以返回小数值或十进制值?

Question: In Swift is there a way to split the string using more than one separator so a single closure can return fractional values or decimal values ?

(继续关闭)

switch (token)) {
case "/"  :
        print( "fraction")

        let pathA = splitString[0]!/splitString[1]!
        return pathA

case "."  :
        print( "decimal")

        let upperSplit = splitString[0]!
        let lowerSplit = splitString[1]! * 0.1  // restore decimal point
        let pathB = upperSplit+lowerSplit
        return pathB
        }
}

推荐答案

如果您打算从无论是十进制表示还是分数,那么就没有需要在小数点处拆分字符串.

If your intention is to create floating point numbers from either a decimal representation or a fraction, then there is no need to split the string at the decimal point.

你可以尝试用Double(string)来转换字符串,如果失败,在斜杠处将其拆分并转换分子和分母分开:

You can try to convert the string with Double(string), and if that fails, split it at the slash and convert numerator and denominator separately:

func doubleFromDecimalOrFraction(s: String) -> Double? {
    // Try to convert from decimal representation:
    if let value = Double(s) {
        return value
    }
    // Try to convert from fractional format:
    if let range = s.range(of: "/"),
        let num = Double(s.substring(to: range.lowerBound)),
        let den = Double(s.substring(from: range.upperBound)) {
        return num/den
    }
    // Invalid format
    return nil
}

(对于无效输入,您可能还没有返回 nil考虑 throw 一个错误,以中止执行fatalError(),或者返回一些默认值.)

(Instead of returning nil for invalid input you might also consider to throw an error, to abort the execution with fatalError(), or to return some default value.)

这个效用函数"然后可以应用于每个数组元素:

This "utility function" can then be applied each array element:

let strings = [ "0.0", "193.16", "5/4", "503.42", "696.58", "25/16", "1082.89", "2/1"]
let values = strings.flatMap(doubleFromDecimalOrFraction)

这篇关于我可以在 Swift 闭包中使用多个分隔符拆分数字字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆