Peter71
Peter71

Reputation: 2300

Get shorter version of for loop?

I'm using Swift 3.0 and have this code for searching an item in an array as an extension of String type:

extension String {
    func equal(compareToArray : [String]) -> Bool {
        for s in compareToArray {
            if self == s {
                return true
            }
        }
        return false
    }
}

It runs fine, but my question is, can I do it better (shorter/more simple or faster)?

Okay, another similar sample:

func contains(compareToArray : [String]) -> Bool {
    for s in compareToArray {
        if self.contains(s) {
            return true
        }
    }
    return false
}

Upvotes: 1

Views: 71

Answers (2)

vadian
vadian

Reputation: 285079

Shorter, simpler, faster

let compareToArray = ["foo", "bar", "baz"]
compareToArray.contains("bar")

Edit:

According to your second example

!compareToArray.filter{ $0.contains("oo") }.isEmpty

compareToArray.index(where: {$0.contains("oo")}) != nil

Upvotes: 6

letanthang
letanthang

Reputation: 420

If you want to check whether an element belong to an Array, in Swift 3.0 this is a better way:

use :

array.index(of: element) -> Int?

Ex:

let myArray = ["a", "b", "c"]
let needle = "b"

if let pos = myArray.index(of: needle') {
  print("\(needle) is in array at position : \(pos)" 
} else {
  print("It's not in array")
}

Upvotes: 0

Related Questions