I am trying to find an item index
by searching a list
. Does anybody know how to do that?
I see there is list.StartIndex
and <
You can filter
an array with a closure:
var myList = [1, 2, 3, 4]
var filtered = myList.filter { $0 == 3 } // <= returns [3]
And you can count an array:
filtered.count // <= returns 1
So you can determine if an array includes your element by combining these:
myList.filter { $0 == 3 }.count > 0 // <= returns true if the array includes 3
If you want to find the position, I don't see fancy way, but you can certainly do it like this:
var found: Int? // <= will hold the index if it was found, or else will be nil
for i in (0..x.count) {
if x[i] == 3 {
found = i
}
}
EDIT
While we're at it, for a fun exercise let's extend Array
to have a find
method:
extension Array {
func find(includedElement: T -> Bool) -> Int? {
for (idx, element) in enumerate(self) {
if includedElement(element) {
return idx
}
}
return nil
}
}
Now we can do this:
myList.find { $0 == 3 }
// returns the index position of 3 or nil if not found
func firstIndex(of element: Element) -> Int?
var alphabets = ["A", "B", "E", "D"]
Example1
let index = alphabets.firstIndex(where: {$0 == "A"})
Example2
if let i = alphabets.firstIndex(of: "E") {
alphabets[i] = "C" // i is the index
}
print(alphabets)
// Prints "["A", "B", "C", "D"]"
In Swift 4, if you are traversing through your DataModel array, make sure your data model conforms to Equatable Protocol , implement the lhs=rhs method , and only then you can use ".index(of" . For example
class Photo : Equatable{
var imageURL: URL?
init(imageURL: URL){
self.imageURL = imageURL
}
static func == (lhs: Photo, rhs: Photo) -> Bool{
return lhs.imageURL == rhs.imageURL
}
}
And then,
let index = self.photos.index(of: aPhoto)
SWIFT 4
Let's say you want to store a number from the array called cardButtons into cardNumber, you can do it this way:
let cardNumber = cardButtons.index(of: sender)
sender is the name of your button