Home > Enterprise >  How to ensure an entity passed to a view conforms to a protocol?
How to ensure an entity passed to a view conforms to a protocol?

Time:12-21

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())
    }
}

CodePudding user response:

You can make the view generic

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

    var body: some View {
        Text("\(entity.getInt())")
    }
}
  • Related