Any Protocol type casting not working

I have a class that conforms to a protocol. But it always fail when I try to cast or verify if it conforms to the protocol.

typealias DeviceHandler = (any Device) -> Void

protocol Device {
    var name: String { get }
}

class DevicesViewModel<T: Device> {
    var devices = [T]()

    func findDevices() {
        DevicesManager.findDevices() { device in
            // casting is failing
            // even if I do device is T, it fails
            guard let device = device as? T else { return }
            self.devices.append(device)
        }
    }
}

class DevicesManager {

    static func findDevices(completion: @escaping DeviceHandler) {
        completion(Computer(name: "Macbook"))
    }
}

class Computer: NSObject, Device {

    var name: String

    init(name: String) {
        self.name = name
        
        super.init()
    }
}

What is the X Type here? There is no declaration of it. I mean is it a struct / class / protocol?

Sorry, it was supposed to be the T

The following code has no type casting failures:

let devicesViewModel = DevicesViewModel<Computer>()
devicesViewModel.findDevices()
print(devicesViewModel.devices.count) // prints 1

If we change DevicesManager's findDevices() implementation to perform completion with something different from Computer Type, then type casting inside DevicesViewModel<Computer> will fail, which is expected.
So assume either provided example is incomplete or there are some additional conditions in the real code.

There is no casting or checking for protocol conformance in provided code sample.
device instance is casted to generic T type constrained with Device protocol, not to a Device protocol itself.

1 Like