How to substring season in a right way?

Hi! I'm trying to extract the season of an episode.

var episodeTitle = "BLACK MIRROR S04 E06"

I tried episodeTitle.components(separatedBy: " ")
["Black", "Mirror", "S04", "E06"]

But I'm missing a right solution, because this splits even the name of the show.

It really depends on the expected arrangement of the string you are trying to parse.

Provided all the strings you will get will be of the form “[title] [season] [episode]”, where [title] may contain any number of spaces, but [season] and [episode] never will, then you can just drop the last two (which you know be the irrelevant season and the episode), and join the rest with spaces again:

let separator = " "
let components = episodeTile.components(separatedBy: separator)
let titleComponentsOnly = components.dropLast(2)
let title = titleComponentsOnly.joined(separator: separator)

You might want to ask if the API you got the string from can vend you the properly capitalized title directly though. The all caps looks kind of ugly and it cannot be reliably undone. In combination with the episode numbers it looks more like an internal identifier to me than something for presenting to users—which is what makes me suspect they may provide exactly what you are looking for elsewhere in the API.

1 Like

I think I expressed myself wrong, but I actually want to keep just components that was dropped (dropLast(2))

Thank you, I found how:

components.suffix(from: components.count-2)

I’m glad you figured it out. I didn’t read quite right either. Your first line did actually say exactly what you want. I just got distracted by the squirrel in the last line.

The documentation for Collection and for Array list all sorts of related methods at your disposal for similar tasks.

The collection ones will work on String too, in case you want to pull the “S” and “E” of the front so you can turn them into Int values or something like that.

Also worth pointing out that Regular Expression is also applicable here.

That's a Collection overload, which only works here because Array uses Int as its Index type. Use the Sequence version to get your exact meaning:

1 Like