简体   繁体   English

Swift检查类是否符合协议始终为true

[英]Swift check if class conforms to protocol always true

protocol Device {
}
protocol ActiveDevice: Device {
}
protocol NoActive: Device {
}

ViewController: 视图控制器:

class ViewController : UIViewController {
  let device: Device
}

Setting device for ViewController. 设置ViewController的设备。 currentDevice is an object which conforms to protocol Device currentDevice是一个符合协议Device的对象

vc.device = currentDevice as! ActiveDevice

Checking if it conforms to the protocol: 检查它是否符合协议:

    if let currentDevice = device as? NoActive  {
        print("Its not active device")
    }else if let currentDevice = device as? ActiveDevice {
        print("Its active device")
    }else {
        print("Its just a device")
    }

It always prints Its not active device what I would expect in this case that it would print Its active device 它总是打印Its not active device ,在这种情况下我会期望打印Its active device

Please check the following code and let me know if this helps. 请检查以下代码,如果有帮助请告诉我。

protocol Device {
}
protocol ActiveDevice: Device {
}
protocol NoActive: Device {
}

// class TestDevice: Device {
// class TestDevice: ActiveDevice {
class TestDevice: NoActive {

}

let currentDevice = TestDevice()

// let device: Device = currentDevice as! ActiveDevice
(It threw error as "Could not cast value of type '__lldb_expr_9.TestDevice' (0x11a2f9090) to '__lldb_expr_9.ActiveDevice' (0x11a6d0628)."). We cannot do this.

let device: Device = currentDevice


if device is NoActive  {
    print("Its not active device")
}else if device is ActiveDevice {
    print("Its active device")
}else {
    print("Its just a device")
}

Now, the output is "Its not active device". 现在,输出是“它不是活动设备”。 And after changing the TestDevice to "ActiveDevice", it printed "Its active device" and so on. 在将TestDevice更改为“ActiveDevice”后,它会打印“其活动设备”等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM