Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extends Set's insert in swift for custom logic

I need to have custom logic in a Set that defines when a Hashable can be insert or not.

First I tried to solve this with a observer

var Tenants: Set<Tenant> = [] {
    willSet {
        // to the business logic here
        // ...

But in an observer i can not return an error. So I tried to extend Set to overwrite the insert method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

extension Set where Element == Tenant {
    @inlinable mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element){

        // .... do my logic here ...

        return (true, newMember)
    }
}

That works so far and the method will be called. I can return true and if my logic did not pass even a false. Ok, but how do I add the Element into the Set? super.insert(). The return is correct, but the Set is empty. How to add the elements into the concrete set?

Implementation so far

/// Global set of known tenants
var Tenants: Set<Tenant> = [] {
    willSet {
        let newTenants = newValue.symmetricDifference(Tenants)
        guard let newTenant = newTenants.first else {
            Logging.main.error("Can not find tenant to add.")
            return
        }
        Logging.main.info("Will add new Tenant \(newTenant.name) [\(newTenant.ident)]")
    }
}

extension Set where Element == Tenant {

    @inlinable mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element){
        print("Check to add...")
        // .... do my logic here ...

        // ok
        return (true, newMember)
    }

}

The result is:

Check to add...
error : Can not find tenant to add.
Check to add...
error : Can not find tenant to add.

>Solution :

This seems to work for "do my logic here"

    self = self.union([newMember])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading