Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple string processing function in Swift 5

Tags:

string

swift

I need a very special (and small) function in Swift 5.

The function will take an arbitrary string as argument, the only thing known about the argument is that it contains at least one of the characters 'a' or 'b'. The function is only interested in the characters 'a' and 'b', ignoring the others. If the last found is an 'a', it returns 'a', if is a 'b' it returns 'b'.

For example, let f be this function.

f("aaa") // returns a.
f("a3242avfvabbba54gg") // returns a.
f("abaagdfb") // returns b.
f("479wfwrvfb8709iho") // returns b.

It is obviously easy to write such a function, but I want to know if there is a particularly clean way in Swift 5 using the last API.

I found the last(where:) method of String, but no sample code to make its usage clear. So I am not sure if that is what I want to use.

like image 884
Michel Avatar asked May 30 '26 19:05

Michel


1 Answers

You are correct that this function can be implemented with last(where:):

func f(_ s: String) -> Character {
    return s.last(where: "ab".contains)!
}

Note that I have used ! to force unwrap because you said there always will be an a or b.

like image 82
Sweeper Avatar answered Jun 02 '26 09:06

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!