Reputation: 11749
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.
Upvotes: 2
Views: 166
Reputation: 271735
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
.
Upvotes: 9