简体   繁体   English

如何确保传递给视图的实体符合协议?

[英]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.我有一个视图可以将几个不同的 NSManagedObject 类型作为输入。 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. A 类和 B 类具有相同的函数 getInt() ,我想在视图中使用该函数。

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

You can make the view generic您可以使视图通用

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM