Last active
June 10, 2018 12:58
-
-
Save alsedi/d6eea4afce2b6b65289840ba5dd0f1d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let content = "abc,cde,5.5,128,256\nefg,ghi,42" | |
let parsedCSV: [[CustomStringConvertible]] = content | |
.components(separatedBy: "\n") | |
.map({ // Step 1 | |
$0.components(separatedBy: ",") | |
.map({ // Step 2 | |
if let int = Int($0) { | |
return int | |
} else if let double = Double($0) { | |
return double | |
} | |
return $0 | |
}) | |
}) | |
print(parsedCSV) | |
// [["abc", "cde", 5.5, 128, 256], ["efg", "ghi", 42]] |
It will also fail for files which use "\r" or "\r\n" instead of "\n".
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It works as long as there are no commas within a string
"abc", "c, de", 5.5, 128
"efg", "ghi", 13.5, 42
It will fail at the string "c, de"