can I split a numeric string using multiple separators in a Swift closure?

前端 未结 3 1582
面向向阳花
面向向阳花 2020-12-07 05:13

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\", \         


        
3条回答
  •  时光取名叫无心
    2020-12-07 06:09

    Split by more than one separator

    Using split

    Swift 4

    let s = "[0, 1, 2, 1]"
    let splitted = s.characters.split { [",", "[", "]"].contains($0.description) }
    

    Swift 3

    let s = "[0, 1, 2, 1]"
    let splitted = s.characters.split { [",", "[", "]"].contains($0.description) }
    

    Swift 2

    let s = "[0, 1, 2, 1]"
    let splitted = s.characters.split(isSeparator: {[",", "[", "]"].contains($0)}) }
    

    Using characterSet

    Swift 4

    let str = "[0, 1, 2, 1]"
    let separatorSet = CharacterSet(charactersIn: ",[]")
    let comps = str.components(separatedBy: separatorSet)
    

    Swift 3

    let str = "[0, 1, 2, 1]"
    let separatorSet = CharacterSet(charactersInString: ",[]")
    let comps = str.components(separatedBy: separatorSet)
    

    Swift 2

    let str = "[0, 1, 2, 1]"
    let separatorSet = NSCharacterSet(charactersInString: ",[]")
    let comps = str.componentsSeparatedByCharactersInSet(separatorSet)
    

    No matter what method we will use, and as a result, you will receive array. Without the information, which separator was used

    If you need only convert String to Double then

    let array = stringArray.compactMap { element -> Double? in
        if let value = Double(element) {
            return value
        }
        let parts = element.components(separatedBy: "/")
        guard parts.count == 2, 
              let dividend = Double(parts[0]), 
              let divisor = Double(parts[1]), 
              divisor != 0
        else {
            return nil
        }
        return dividend / divisor
    }
    

提交回复
热议问题