Swift Erase with Common Enumeration and Common Protocol

I had to use style erasure in Swift several times, but it always used a common protocol. In this case, it includes an enum as a general , and and the common protocol, and I was very puzzled.

Here is my general general and general protocol with the necessary extension:

enum UIState<T> {
    case Loading
    case Success([T])
    case Failure(ErrorType)
}

protocol ModelsDelegate: class {
    associatedtype Model
    var state: UIState<[Model]> { get set }
}

extension ModelsDelegate {

    func getNewState(state: UIState<[Model]>) -> UIState<[Model]> {
        return state
    }

    func setNewState(models: UIState<[Model]>) {
        state = models
    }
}

And here my type erases the general class:

class AnyModelsDelegate<T>: ModelsDelegate {
    var state: UIState<[T]> {

        get { return _getNewState(UIState<[T]>) }  // Error #1
        set { _setNewState(newValue) }
    }

    private let _getNewState: ((UIState<[T]>) -> UIState<[T]>)
    private let _setNewState: (UIState<[T]> -> Void)

    required init<U: ModelsDelegate where U.Model == T>(_ models: U) {
        _getNewState = models.getNewState
        _setNewState = models.setNewState
    }
}

I get the following errors (they are marked in the sample code):

Error No. 1:

Cannot convert value of type '(UIState<[T]>).Type' (aka 'UIState<Array<T>>.Type') to expected argument type 'UIState<[_]>' (aka 'UIState<Array<_>>')

I worked on this for a while, and in this code there were quite a few variations that “almost worked”. The error is always related to the recipient.

+4
source share
1 answer

, , @dan , , , :

get { return _getNewState(UIState<[T]>) }

, , ? , _getNewState () -> UIState<[T]> :

get { return _getNewState() }

, getNewState setNewState(_:) , state - , erasure init:

_getNewState = { models.state }
_setNewState = { models.state = $0 }

( , models, . Closures: Capturing Values ​​)

, , UIState<T>, UIState<[T]> , T , .Success ( 2D-).

, , , :

enum UIState<T> {
    case Loading
    case Success([T])
    case Failure(ErrorType)
}

protocol ModelsDelegate: class {
    associatedtype Model
    var state: UIState<Model> { get set }
}

class AnyModelsDelegate<T>: ModelsDelegate {
    var state: UIState<T> {
        get { return _getNewState() }
        set { _setNewState(newValue) }
    }

    private let _getNewState: () -> UIState<T>
    private let _setNewState: (UIState<T>) -> Void

    required init<U: ModelsDelegate where U.Model == T>(_ models: U) {
        _getNewState = { models.state }
        _setNewState = { models.state = $0 }
    }
}
+3

Source: https://habr.com/ru/post/1651095/


All Articles