Skip to content

Commit d839794

Browse files
authored
Merge pull request swiftlang#1623 from RobertPieta/NSOrderedSet_NSSet.isSubset_performance
2 parents 206636b + 9ad0048 commit d839794

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

Foundation/NSOrderedSet.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,11 @@ extension NSOrderedSet {
224224
}
225225

226226
open func isSubset(of other: NSOrderedSet) -> Bool {
227+
// If self is larger then self cannot be a subset of other
228+
if count > other.count {
229+
return false
230+
}
231+
227232
for item in self {
228233
if !other.contains(item) {
229234
return false
@@ -233,6 +238,11 @@ extension NSOrderedSet {
233238
}
234239

235240
open func isSubset(of set: Set<AnyHashable>) -> Bool {
241+
// If self is larger then self cannot be a subset of set
242+
if count > set.count {
243+
return false
244+
}
245+
236246
for item in self {
237247
if !set.contains(item as! AnyHashable) {
238248
return false

Foundation/NSSet.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,11 @@ extension NSSet {
208208
}
209209

210210
open func isSubset(of otherSet: Set<AnyHashable>) -> Bool {
211+
// If self is larger then self cannot be a subset of otherSet
212+
if count > otherSet.count {
213+
return false
214+
}
215+
211216
// `true` if we don't contain any object that `otherSet` doesn't contain.
212217
for item in self {
213218
if !otherSet.contains(item as! AnyHashable) {

TestFoundation/TestNSSet.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class TestNSSet : XCTestCase {
2525
("test_CountedSetRemoveObject", test_CountedSetRemoveObject),
2626
("test_CountedSetCopying", test_CountedSetCopying),
2727
("test_mutablesetWithDictionary", test_mutablesetWithDictionary),
28+
("test_Subsets", test_Subsets)
2829
]
2930
}
3031

@@ -224,4 +225,16 @@ class TestNSSet : XCTestCase {
224225
dictionary.setObject(aSet, forKey: key)
225226
XCTAssertNotNil(dictionary.description) //should not crash
226227
}
228+
229+
func test_Subsets() {
230+
let set = NSSet(array: ["foo", "bar", "baz"])
231+
let otherSet = NSSet(array: ["foo", "bar"])
232+
let otherOtherSet = Set<AnyHashable>(["foo", "bar", "baz", "123"])
233+
let newSet = Set<AnyHashable>(["foo", "bin"])
234+
XCTAssert(otherSet.isSubset(of: set as! Set<AnyHashable>))
235+
XCTAssertFalse(set.isSubset(of: otherSet as! Set<AnyHashable>))
236+
XCTAssert(set.isSubset(of: otherOtherSet))
237+
XCTAssert(otherSet.isSubset(of: otherOtherSet))
238+
XCTAssertFalse(newSet.isSubset(of: otherSet as! Set<AnyHashable>))
239+
}
227240
}

0 commit comments

Comments
 (0)