Skip to content

Commit 68f2d07

Browse files
Add quotes to description where required (#86)
* Add tests for description with quotes * Add quotes to description for values with commas Co-authored-by: Christian Tietze <[email protected]>
1 parent 22dc4dd commit 68f2d07

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

SwiftCSV/Description.swift

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,20 @@ import Foundation
1111
extension CSV: CustomStringConvertible {
1212
public var description: String {
1313
let head = header.joined(separator: ",") + "\n"
14-
1514
let cont = namedRows.map { row in
16-
header.map { row[$0]! }.joined(separator: ",")
15+
return header.map { key -> String in
16+
let value = row[key]!
17+
18+
// Add quotes if value contains a comma
19+
if value.contains(",") {
20+
return "\"\(value)\""
21+
}
22+
return value
23+
24+
}.joined(separator: ",")
25+
1726
}.joined(separator: "\n")
1827
return head + cont
1928
}
2029
}
30+

SwiftCSVTests/CSVTests.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,12 @@ class CSVTests: XCTestCase {
8282
func testDescription() {
8383
XCTAssertEqual(csv.description, "id,name,age\n1,Alice,18\n2,Bob,19\n3,Charlie,20")
8484
}
85-
85+
86+
func testDescriptionWithDoubleQuotes() {
87+
csv = try! CSV(string: "id,name,age\n1,\"Alice, In, Wonderland\",18\n2,Bob,19\n3,Charlie,20")
88+
XCTAssertEqual(csv.description, "id,name,age\n1,\"Alice, In, Wonderland\",18\n2,Bob,19\n3,Charlie,20")
89+
}
90+
8691
func testEnumerate() throws {
8792
let expected = [
8893
["id": "1", "name": "Alice", "age": "18"],

0 commit comments

Comments
 (0)