derdida
derdida

Reputation: 14904

Find Index of Array by NSDate?

I would like to find out the index of an array by an NSDate.

Ill tried:

var sectionsInTable = [NSDate]()

let indexOfElement = sectionsInTable.indexOf(date) // where date is an NSDate in my sectionsInTable Array

print(indexOfElement)

But ill always get false

How is it possible to get the index of an NSDate from an array?

Thanks in advance.

Upvotes: 0

Views: 260

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Your approach should work fine. This code produces an index of 2:

let s = 31536000.0 // Seconds per Year
var tbl = [NSDate]()
tbl.append(NSDate(timeIntervalSince1970: 40*s)) // 0
tbl.append(NSDate(timeIntervalSince1970: 41*s)) // 1
tbl.append(NSDate(timeIntervalSince1970: 42*s)) // 2
tbl.append(NSDate(timeIntervalSince1970: 43*s)) // 3

let date = NSDate(timeIntervalSince1970: 42*s)
let indexOfElement = tbl.indexOf(date)

The most likely reason that you are not getting the proper index is that your search NSDate has a time component that does not match the time component in NSDate objects in the array. You can confirm that this is the case by printing both objects, and verifying their time component.

Upvotes: 1

Yury
Yury

Reputation: 6114

If you have exact copies of NSDate objects, your code should work:

let date = NSDate()
let date2 = date.copy() as! NSDate
var sectionsInTable: [NSDate] = [date]

let indexOfElement = sectionsInTable.indexOf(date2)
print(indexOfElement)
//prints: Optional(0)

Upvotes: 1

Puran
Puran

Reputation: 994

Since comparison depends on how deep you want to go with date time thing. I think you should just loop through your date array and compare if it's equal and return that index.

Upvotes: 0

Related Questions