swiftgenericsenumsassociated-value

Enums associated values and generics


I have a enum like this, it contains different initial states:

enum InitialState {
    case listTableView(ListTableViewState)   
}

I want to use them like this:

var tableViewState: ListTableViewState?

let test = ListTableViewState(group: .large, statIntervalBase: StatIntervalBaseModel(stat: "ppc", interval: "24h", base: "usd"), order: .ascending, searchParameter: "", quantityStats: .six)
let test1 = InitialState.listTableView(test)
tableViewState = loadInitialState(inital: test1)

This is the generic function I am using:

func loadInitialState<T>(inital: InitialState) -> T  {
    let test = inital as! T
    print(test)
    return test
}

I get this error of course:

Could not cast value of type 'InitialState' (0x109466da0) to 'ListTableViewState' (0x1094912b0).

How can I access it in the generic function loadInitialState?


Solution

  • Reason for Exception:

    In the below code,

    let test = inital as! T
    

    You are casting InitialState type to T. And according to your code the type of the generic type T is ListTableViewState.

    The reason T is of type ListTableViewState is derived from,

    tableViewState = loadInitialState(inital: test1)
    

    Here, tableViewState is of type ListTableViewState

    This is the reason type-casting to a different type fails and throws an exception.

    Solution:

    You can access the associated value of an enum case using the switch statement, i.e.

    func loadInitialState<T>(inital: InitialState) -> T?  {
        switch inital {
        case .listTableView(let test):
            return test as? T
        }
        return nil
    }