2

I can't understand the problem with Swift Generic

Here is my snippet of code

protocol StateClient: class {
    func update<NewState: State, PrevState: State>(state: NewState, prevState: PrevState)
}

protocol State {
    init(client: StateClient)
}

protocol ProfileState: State {
    var isActiveState: Bool { get }
    var isInactiveState: Bool { get }

    func setActiveState()
    func setInactiveState()
}

extension State {

    func setState<T: State, C: StateClient>(class: T.Type, client: C?) {
        guard let client = client else {
            return
        }
        let newState = T(client: client)
        client.update(state: newState, prevState: self)
    }

}
// - Implementation

struct InactiveState: ProfileState {
    private weak var client: StateClient?
    var isActiveState: Bool = false
    var isInactiveState: Bool = true

    init(client: StateClient) {
        self.client = client
    }

    func setActiveState() {
        setState(class: ActiveState.self, client: client)
    }

    func setInactiveState() {

    }

}

struct ActiveState: ProfileState {
    private weak var client: StateClient?
    var isActiveState: Bool = true
    var isInactiveState: Bool = false

    init(client: StateClient) {
        self.client = client
    }

    func setActiveState() {

    }

    func setInactiveState() {

    }
}

I can't compile the code above. The error :

error: MyPlayground22.playground:38:51: error: in argument type 'StateClient?', 'StateClient' does not conform to expected type 'StateClient' setState(class: ActiveState.self, client: client)"

What's wrong ? Any advice would be appreciated)

Hamish
  • 78,605
  • 19
  • 187
  • 280
Ilya
  • 141
  • 1
  • 9
  • 1
    [Protocols don't always conform to themselves](https://stackoverflow.com/a/43408193/2976878) – `StateClient` is not a type that conforms to `StateClient`. As far as I can tell though, `setState` doesn't need the generic placeholder `C` – just have the `client:` parameter take a `StateClient?`. – Hamish Oct 12 '17 at 14:43
  • Thank you a lot. It's really helped – Ilya Oct 13 '17 at 06:13

0 Answers0