Skip to content

Instantly share code, notes, and snippets.

@alsedi
Last active June 10, 2018 12:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alsedi/d6eea4afce2b6b65289840ba5dd0f1d4 to your computer and use it in GitHub Desktop.
Save alsedi/d6eea4afce2b6b65289840ba5dd0f1d4 to your computer and use it in GitHub Desktop.
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]]
@Mizhou
Copy link

Mizhou commented Jun 10, 2018

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"

@Mizhou
Copy link

Mizhou commented Jun 10, 2018

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