Reputation: 3163
I'm trying to use the find
function to get the index of a CKRecord in an array. However I'm running into a problem that I don't understand.
I have two arrays: notes
and allNotes
. notes
is a subset of allNotes
. I have an item from notes
and I'm trying to find its index within allNotes
. As you can see from the output it exists in both arrays, but its only being found in the notes
array.
func removeNoteAtIndexPath(indexPath: NSIndexPath) {
let note = tableViewController.notes[indexPath.row]
if let index = find(allNotes, note) {
println("Found in allNotes")
} else {
println("Not found in allNotes")
}
if let index = find(tableViewController.notes, note) {
println("Found in notes")
} else {
println("Not found in notes")
}
println(tableViewController.notes[0])
println(allNotes[0])
}
Console output
Not found in allNotes
Found in notes
<CKRecord: 0x7fb49ad37120; recordType=Note, recordID=E6BD60A1-AB15-4952-84A3-81BDB4DFC961:(_defaultZone:__defaultOwner__), recordChangeTag=i8nh54t3, values={
Text = "My note";
}>
<CKRecord: 0x7fb49ac31f60; recordType=Note, recordID=E6BD60A1-AB15-4952-84A3-81BDB4DFC961:(_defaultZone:__defaultOwner__), recordChangeTag=i8nh54t3, values={
Text = "My note";
}>
Upvotes: 0
Views: 323
Reputation: 3163
I like Satachito's answer better, but this was my initial solution:
func findCKRecord(records: [CKRecord], record: CKRecord) -> Int? {
var index: Int?
let recordID = record.recordID
for (i, record) in enumerate(records) {
let currentRecordID = record.recordID
if recordID == currentRecordID {
index = i
}
}
return index
}
Upvotes: 0
Reputation: 5888
You need to adapt Equatable protocol to CKRecord like below.
extension CKRecord: Equatable {}
public func
==( lhs: CKRecord, rhs: CKRecord ) -> Bool {
return lhs.recordID.recordName == rhs.recordID.recordName
}
Upvotes: 1