Skip to content

Improved performance of isSubset for NSOrderedSet and NSSet #1623

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Foundation/NSOrderedSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,11 @@ extension NSOrderedSet {
}

open func isSubset(of other: NSOrderedSet) -> Bool {
// If self is larger then self cannot be a subset of other
if count > other.count {
return false
}

for item in self {
if !other.contains(item) {
return false
Expand All @@ -219,6 +224,11 @@ extension NSOrderedSet {
}

open func isSubset(of set: Set<AnyHashable>) -> Bool {
// If self is larger then self cannot be a subset of set
if count > set.count {
return false
}

for item in self {
if !set.contains(item as! AnyHashable) {
return false
Expand Down
5 changes: 5 additions & 0 deletions Foundation/NSSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,11 @@ extension NSSet {
}

open func isSubset(of otherSet: Set<AnyHashable>) -> Bool {
// If self is larger then self cannot be a subset of otherSet
if count > otherSet.count {
return false
}

// `true` if we don't contain any object that `otherSet` doesn't contain.
for item in self {
if !otherSet.contains(item as! AnyHashable) {
Expand Down
13 changes: 13 additions & 0 deletions TestFoundation/TestNSSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class TestNSSet : XCTestCase {
("test_CountedSetRemoveObject", test_CountedSetRemoveObject),
("test_CountedSetCopying", test_CountedSetCopying),
("test_mutablesetWithDictionary", test_mutablesetWithDictionary),
("test_Subsets", test_Subsets)
]
}

Expand Down Expand Up @@ -224,4 +225,16 @@ class TestNSSet : XCTestCase {
dictionary.setObject(aSet, forKey: key)
XCTAssertNotNil(dictionary.description) //should not crash
}

func test_Subsets() {
let set = NSSet(array: ["foo", "bar", "baz"])
let otherSet = NSSet(array: ["foo", "bar"])
let otherOtherSet = Set<AnyHashable>(["foo", "bar", "baz", "123"])
let newSet = Set<AnyHashable>(["foo", "bin"])
XCTAssert(otherSet.isSubset(of: set as! Set<AnyHashable>))
XCTAssertFalse(set.isSubset(of: otherSet as! Set<AnyHashable>))
XCTAssert(set.isSubset(of: otherOtherSet))
XCTAssert(otherSet.isSubset(of: otherOtherSet))
XCTAssertFalse(newSet.isSubset(of: otherSet as! Set<AnyHashable>))
}
}