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

How to ensure an entity passed to a view conforms to a protocol?

I have a view that can take a couple different NSManagedObject types as an input. Each of these classes has a function that returns a value. I’d like to be able to pass either of these classes to the view and use this function. So, I believe I need to enforce that the passed object conforms to a protocol.

A simplified example of what I’m trying to do is below. Classes A and B have the same function getInt() and I want to use that function within a view.

extension ClassA: returnsInt {
    func getInt() -> Int {
        return 1
    }
}

extension ClassB: returnsInt {
    func getInt() -> Int {
        return 1
    }
}

protocol returnsInt {
    func getInt() -> Int
}

struct RandomView: View {
    
    @ObservedObject var entity: // NSManagedObject that conforms to the returnsInt protocol

    var body: some View {
        
        Text(entity.getInt())
    }
}

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

>Solution :

You can make the view generic

struct RandomView<Entity: NSManagedObject & returnsInt>: View {
    @ObservedObject var entity: Entity

    var body: some View {
        Text("\(entity.getInt())")
    }
}
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