Skip to content

Commit 9087d5c

Browse files
committed
Merge pull request #276 from HeMet/nsarray-indexOfObject-fix
Fixes wrong behavior of NSArray.indexOfObject…
2 parents f2672a7 + bf247af commit 9087d5c

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

Foundation/NSArray.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -543,15 +543,15 @@ public class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NS
543543
}
544544
}
545545

546-
guard searchForInsertionIndex && lastEqual else {
546+
if !searchForInsertionIndex {
547547
return result
548548
}
549549

550-
guard result == NSNotFound else {
551-
return result + 1
550+
if result == NSNotFound {
551+
return indexOfLeastGreaterThanObj
552552
}
553553

554-
return indexOfLeastGreaterThanObj
554+
return lastEqual ? result + 1 : result
555555
}
556556

557557

TestFoundation/TestNSArray.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,14 @@ class TestNSArray : XCTestCase {
156156
let rangeLength = 13
157157
let endOfArray = objectIndexInArray(array, value: 10, startingFrom: rangeStart, length: rangeLength, options: [.InsertionIndex, .LastEqual])
158158
XCTAssertTrue(endOfArray == (rangeStart + rangeLength), "...or the index at the end of the array if the object is larger than all other elements.")
159+
160+
let arrayOfTwo = NSArray(array: [NSNumber(int: 0), NSNumber(int: 2)])
161+
let indexInMiddle = objectIndexInArray(arrayOfTwo, value: 1, startingFrom: 0, length: 2, options: [.InsertionIndex, .FirstEqual])
162+
XCTAssertEqual(indexInMiddle, 1, "If no match found item should be inserted before least greater object")
163+
let indexInMiddle2 = objectIndexInArray(arrayOfTwo, value: 1, startingFrom: 0, length: 2, options: [.InsertionIndex, .LastEqual])
164+
XCTAssertEqual(indexInMiddle2, 1, "If no match found item should be inserted before least greater object")
165+
let indexInMiddle3 = objectIndexInArray(arrayOfTwo, value: 1, startingFrom: 0, length: 2, options: [.InsertionIndex])
166+
XCTAssertEqual(indexInMiddle3, 1, "If no match found item should be inserted before least greater object")
159167
}
160168

161169

0 commit comments

Comments
 (0)