2

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.

0

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah! That's the best answer I could hope for, short and it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.