-1

I'm trying to create filter functionality using Swift. I have many filter types like Location, Skill, etc. So I'm planning to generalize this using a protocol.

protocol FilterProtocol {
    var text: String { get set }
    var count: String? { get set }
    var isSelected: Bool { get set }
}

extension FilterProtocol: Identifiable {
    var id: String  { text }
}

struct LocationFilter: FilterProtocol {
    var text: String
    var count: String?
    var isSelected: Bool
}  

But I am getting error Extension of protocol 'FilterProtocol' cannot have an inheritance clause

Paulw11
  • 108,386
  • 14
  • 159
  • 186
user8719510
  • 133
  • 2
  • 12
  • 1
    Do not make a substantial change to your question after it has already been answered. Simply ask another question – Paulw11 Jun 29 '22 at 12:12
  • Can't figure out why sometimes swift allows it and other times it doesn't. I added a protocol extension in a file, built ran with no problem. Moved it to a separate file and then the error :( – Mercutio Jul 01 '22 at 16:59

1 Answers1

2

Just move the conformance to the declaration:

protocol FilterProtocol: Identifiable {
    var text: String { get set }
    var count: String? { get set }
    var isSelected: Bool { get set }
}

extension FilterProtocol {
    var id: String  { text }
}

another variant if we consider to make just provided part of code compilable... there might be many variants (depending on final needs and that's out of topic):

protocol FilterProtocol {
    var text: String { get set }
    var count: String? { get set }
    var isSelected: Bool { get set }
}

extension FilterProtocol {      // << just extension
    var id: String  { text }
}

struct LocationFilter: FilterProtocol {
    var text: String
    var count: String?
    var isSelected: Bool
}

struct FilterView: View {

    let filters: [FilterProtocol] = []   // << non-generic

    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Text("By Location")
                    .font(.headline)
                Spacer()
                Button(action: {}) {
                    Image(systemName: "arrowtriangle.down.circle")
                }
            }
            ForEach(filters, id: \.id) { filter in  // << explicit .id
                HStack {
                    Text(filter.text)
                    Text(filter.count ?? "")

                }
            }
        }.padding()
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690