Caspert Caspert - 1 year ago 70
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
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 Source

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

let str = "2007-2016"

if let index = str.characters.index(of: "-") {
    let year = str.substring(to: index)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download