Get an item in a set with a "member"

I'm new to Swift, and I'm trying to rewrite a piece of Objective-C code in Swift. The source code changes the element in Set:

@property (nonatomic, strong, nonnull) NSMutableSet<CustomItem *> *itemsSet;
...

CustomItem *item = [[CustomItem alloc] initWithSomething:something];
CustomItem *existingItem = [self.itemsSet member:item];
if (existingItem) {
    existingItem.property = 3
}

Swift code looks something like this:

var itemsSet = Set<CustomItem>()
...

let item = CustomItem(something: something)
let existingItem = self.itemsSet...?

Is it possible to get a Set element in the same way using Swift?

+4
source share
2 answers

Unfortunately, I do not know why this is not working properly. I would suggest that Swift Setalso has a function member- apparently it is not .

The module documentation Swiftsays:

/// A shadow for the "core operations" of NSSet.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSSet` subclass.
@objc public protocol _NSSetCoreType : _NSCopyingType, _NSFastEnumerationType {
    public init(objects: UnsafePointer<AnyObject?>, count: Int)
    public var count: Int { get }
    public func member(object: AnyObject) -> AnyObject?
    public func objectEnumerator() -> _NSEnumeratorType
    public func copyWithZone(zone: _SwiftNSZone) -> AnyObject
    public func countByEnumeratingWithState(state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int) -> Int
}

which sounds like all of these features are not available in Swift (I could be wrong about that, but it seems to be true).

- NSMutableSet ( , Objective-C):

var itemsSet : NSMutableSet = NSMutableSet()
itemsSet.addObject("bla")
let existingItem = itemsSet.member("bla")

- , "Swift ":

let item = CustomItem(something: "")
if let index = itemsSet.indexOf(item) {
    let existingItem = itemsSet[index]
    existingItem.something = "somethingElse"
}
+3

indexOf() - luk2302, - .

: member() NSSet, Set NSSet :

if let existingItem = (itemsSet as NSSet).member(item) as? CustomItem {
    existingItem.something = "somethingElse"
}
+2

Source: https://habr.com/ru/post/1626430/


All Articles