jimmy0251 jimmy0251 - 28 days ago 4x
Swift Question

Swift: Can not use array filter in if let statement condition

Suppose I have an array of user's names

let users = ["Hello", "1212", "12", "Bob", "Rob"]

I want to get the first user whose name length is 2, so I filtered the array and got the first user

if let selected = users.filter{$0.characters.count == 2}.first {

This code is throwing a compilation error under swift 2.2

Consecutive statements on a line must be separated by ';'

However, this is working fine though

let selected = users.filter{$0.characters.count == 2}.first
if let selected = selected {

Can anyone explain why do I need to store filter result in a separate variable first? Any help would be really appreciated.


You can make this work by putting parentheses around the closure that you're passing to filter:

if let selected = users.filter({$0.characters.count == 2}).first {

That is the right way to do it. The trailing closure syntax doesn't work very well sometimes on lines with extra elements. You could also put parentheses around the whole statement:

if let selected = (users.filter {$0.characters.count == 2}.first) {

Swift is just having trouble parsing your statement. The parentheses give it help in how to parse the line. You should prefer the first way since the closure is indeed a parameter of filter, so enclosing it in parentheses makes it clear to Swift that you are passing it to filter.