Idiomatic way to work with substrings?

I find it hard to write good Swift code, aka, that reads easy and is not long to do this:

I have a domain name, that could potentially hold one or more subdomains, so not just "irc.libera.chat" but it could be also "a.b.c.whatever.com".

What I want to do is extract the domain, so that means only the word before and after the last dot, with the dot itself included "libera.chat" and "whatever.com"

How would you do that in Swift?

1 Like

The current way I do it is:

let domain = "irc.libera.chat"

let words = domain.split(separator: ".")

let dom = words[words.count - 2] + "." + words[words.count-1]

I guess another alternative would be:

let domain = "irc.libera.chat"

let words = domain.split(separator: ".")

words.suffix(2).joined(separator: ".")

Not sure which one looks better, or if there is a better one

1 Like

Another alternative, which wouldn't require you to reconstruct the string by adding the dot back, would be to find the index of the second to last word, and use that to grab the substring. It also gives you nice place to handle the errors

    let domain = "irc.libera.chat"
    guard let idx = domain.split(separator: ".").dropLast().last?.startIndex else {
        // handle strings without any dots
    }
    let substring = domain[idx...]
3 Likes