penangite
penangite

Reputation: 33

Swift 4: Using Swift.contains to check existence of a Character in a String

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'.

Upvotes: 1

Views: 821

Answers (1)

Sweeper
Sweeper

Reputation: 271625

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.

Upvotes: 3

Related Questions