Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

swift2

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 {
   print(selected)
}

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 {
   print(selected)
}

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

like image 553
jimmy0251 Avatar asked Sep 27 '16 00:09

jimmy0251


1 Answers

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 {
    print(selected)
}

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) {
    print(selected)
}

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.

like image 90
vacawama Avatar answered Nov 10 '22 19:11

vacawama