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

时间:2019-04-04 11:00:58

标签: ios swift swift-protocols

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

ViewController:

class ViewController : UIViewController {
  let device: Device
}

ViewController的设置设备。 currentDevice是符合协议Device的对象

vc.device = currentDevice as! ActiveDevice

检查其是否符合协议:

    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")
    }

它总是打印Its not active device,在这种情况下,它会打印Its active device

1 个答案:

答案 0 :(得分:0)

请检查以下代码,并告诉我是否有帮助。

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")
}

现在,输出为“其不是活动设备”。然后将TestDevice更改为“ ActiveDevice”,然后打印“ Its active device”,依此类推。