maxnormal
maxnormal

Reputation: 75

Better way to handle multiple OR statements

Is there a better way to write this code in Swift? I am filtering newsCore based on the contents of activeSources array.

let foundSources = newsCore.filter { $0[3] as! String == activeSources[0] || $0[3] as! String == activeSources[1] || $0[3] as! String == activeSources[2] || $0[3] as! String == activeSources[3] || $0[3] as! String == activeSources[4] || $0[3] as! String == activeSources[5] || $0[3] as! String == activeSources[6] || $0[3] as! String == activeSources[7] || $0[3] as! String == activeSources[8] || $0[3] as! String == activeSources[9] || $0[3] as! String == activeSources[10] || $0[3] as! String == activeSources[11] || $0[3] as! String == activeSources[12] || $0[3] as! String == activeSources[13] || $0[3] as! String == activeSources[14] || $0[3] as! String == activeSources[15] || $0[3] as! String == activeSources[16]}

Upvotes: 0

Views: 33

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can use contains instead of or-ing array items individually

let foundSources = newsCore.filter { activeSources.contains($0[3] as! String) }

Tip:Think of a proper data type/model instead of $0[3] as! String

Upvotes: 2

Related Questions