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
either fractional (see earlier post)
let splitStrings = s.characters.split(separator: "/").map(String.init).map({ Double($0) })
or decimal
let splitStrings = s.characters.split(separator: ".").map(String.init).map({ Double($0) })
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 ?
(continuation of closure)
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.
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:(Instead of returning
nil
for invalid input you might also consider tothrow
an error, to abort the execution withfatalError()
, or to return some default value.)This "utility function" can then be applied each array element:
Split by more than one separator
Using
split
Swift 4
Swift 3
Swift 2
Using characterSet
Swift 4
Swift 3
Swift 2
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
Define extension (Swift 4):
Usage:
Result :
["aaa", "bbb", "ccc", "ffffd"]