swift generic and associated type in protocols

58 Views Asked by At

I have several situations in my app, that I want to show information to the user. Information in all cases will contain a title, and several rows, each row will have a key and value that I want to format value in some way. for example:

title 1
-----
amount: 1,000 $
time: 2020/12/12
...
title 2
-----
name: Roberto Carlos
status: active
...

I'm trying to use a view controller to show this stuff in a swifty way. So I abstract a data type like this:

protocol InquiryRepresentableProtocol {
    associatedtype Title: RawRepresentable<String>
    associatedtype Row: RawRepresentable<String>
    associatedtype DataType: InquiryRowResultProtocol<Row>

    var title: Title { get }
    var rows: [Row] { get }
    var data: DataType { get }
}

the "data" above is what ever that implements a protocol like this:

protocol InquiryRowResultProtocol<Row> {
    associatedtype Row: RawRepresentable<String>
    func getRowResultFor(row: Row) -> [String]
    func getDefinedRows() -> [Row]
}

it can respond to a subset of string enum cases as a formatted string. maybe this code can clarify more:

enum RowsForSituation1: String {
   case cost = "amount"
   case date = "time"
}

struct MyModel: InquiryRowResultProtocol {
    let value: Int

    func getRowResultFor(row: RowsForSituation1) -> String {
        switch row {
        case .cost:
            return "\(self.value)".myCustomForamatting()
        default:
            fatalError()
    }

    func getDefinedRows() -> [RowsForSituation1] {
        return [.cost]
    }
}

now the problem I'm trying to solve: when I want to implement a concrete type that implements "InquiryRepresentableProtocol", I get errors related to generics and stuff:

struct TransferInquiryModel: InquiryRepresentableProtocol {
    let title: TransferInquiryTitle
    let rows: [TransferInquiryRow]
    let data: InquiryPopupRowResultProtocol<TransferInquiryRow>
}

this is the errors I get:

Type 'TransferInquiryModel' does not conform to protocol 'InquiryRepresentableProtocol'

and

Use of protocol 'InquiryRowResultProtocol<TransferInquiryPopupRow>' as a type must be written 'any InquiryRowResultProtocol<TransferInquiryPopupRow>'

I will appreciate any help or guide about this.

0

There are 0 best solutions below