1

I would like to check whether a String contains any of the characters 'a', 'e', 'i', 'o' or 'u'.

I understand that the code to write it is:

let target : String = "monocle"
let ok : Bool = target.contains {"aeiou".contains($0)}
// more codes to use the Boolean value of variable 'ok'

Can anyone explain what actually goes on in the second line of the code, i.e. the initialization of the variable ok ?

Edit: To be more specific, I was hoping to find out what actually goes on inside the closure. Thanks to the answer from Sweeper, I now understand that it means checking the String target, character by character (using shorthand argument name $0), for any of the characters 'a', 'e', 'i', 'o' or 'u'.

1

1 Answer 1

3

You first need to understand the concept of "passing a closure to a method" because that is exactly what is happening in the second line.

String.contains can accept a closure of the type Character -> Bool. It will apply the closure on each character of the string and see what it returns. If the closure, when applied to any of the characters, returns true, then contains returns true. Otherwise, false.

This is the closure you are passing in:

{"aeiou".contains($0)}

$0 means the first argument. It checks if the character passed in is one of aeiou. So imagine this closure gets applied to each character in the string to test, and when that returns true, contains returns true.

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

1 Comment

Also, wrapping in closure and using $0 is not really necessary here. target.contains("aeiou".contains) will work too.

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.