Search code examples
swiftcsvswift3

How do I get the last value in a string separated by commas?


I have this string

let data = 123,456,7,8,9,10

I want to extract the last value separated by a "," which in this case would be 10, and its not necessarily a two digit value.

I tried this:

var data = 123,456,7,8,9,10
data = data.last!

Solution

  • Use String method data.components(separatedBy:)

    let data = "123,456,7,8,9,10"
    let lastComponent = data.components(separatedBy: ",").last
    print(lastComponent)