Skip to content

Latest commit

 

History

History

CommaSeparatedList

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Get a Comma Separated List From An Array

Stop writing rubbish!

Photo by The New York Public Library on Unsplash
Photo by The New York Public Library on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Here is a friendly YouTube version: https://youtu.be/cW7jpnRQefg

Not great

Here I can loop through the input Strings, adding the comma to each element in turn.

But there is a wrinkle in this! The last element would have a comma appended to the end! This is then removed with a quick outputString.removeLast().

The potential function is shown here:

func commaSeparatedList(list: [String]) -> String {
    var outputString: String = ""
    for element in list {
    	outputString.append(element + ",")
    }
    outputString.removeLast()
    return outputString
}

Better

We can use a map combined with String interpolation to join the elements with a comma.

Here is the end result:

func commaSeparatedList(list: [String]) -> String {
    var outputString: String = ""
    outputString.append(list.map{ "\($0)" }.joined(separator: ","))
    return outputString
}

Testing

This wouldn't be a great article without some testing! The following works only in a playground (which is why we hit defaultTestSuite) and more testing information is avaliable in my TDD article, but in any case here is the code:

class MyTests: XCTestCase {
    func testCSLSingle() {
        XCTAssertEqual(commaSeparatedList(list: ["a"]), "a")
    }
    func testCSLDouble() {
        XCTAssertEqual(commaSeparatedList(list: ["a", "b"]), "a,b")
    }
    
    func testCSLTriple() {
        XCTAssertEqual(commaSeparatedList(list: ["a", "b", "c"]), "a,b,c")
    }
}

MyTests.defaultTestSuite.run()

Conclusion

Writing readable code is always a worthwhile endeavor.

Writing good, reliable code is really worthwhile, and spending time making sure that your code is up to scratch will help your PR's go through. Isn't that worth thinking about?

If you've any questions, comments or suggestions please hit me up on Twitter