Caspert Caspert - 8 days ago 7
Swift Question

How to get the first word before a dash in Swift?

I would like to get the first year of this string. The one before the dash

-
: "2007-2016"

How can I achieve this within Swift 3?

I did some research and there is an function called
substring
or
index
but doesn't know which one I should use.

What I want to achieve is a sort function that will sort on year. So I think the best way to do this is using the first year (from year). There are also objects that only contains one year...

Answer

Use index(of:) and substring(to:), example:

let str = "2007-2016"

if let index = str.characters.index(of: "-") {
    let year = str.substring(to: index)
    print(year)
}
Comments