1

I tried to downcasting from Any type to UIAccessibilityIdentification but always failed

let button: Any = UIButton(frame: CGRect.zero)
let accessIden = button as? UIAccessibilityIdentification

Result always nil.

I don't known the reason for this.

Can anyone explain?

Thanks,

user2353285
  • 75
  • 1
  • 7
  • Instead of `let button: Any = UIButton(frame: CGRect.zero)` use `let button = UIButton(frame: CGRect.zero)` – Midhun MP Jan 08 '19 at 04:29
  • Yes. But i need cast from Any type. Can you explain why we can not cast from Any type. Do you have any solution if we need cast from Any type. – user2353285 Jan 08 '19 at 04:31
  • In that case you can use `let button: UIControl = UIButton(frame: CGRect.zero)` – Midhun MP Jan 08 '19 at 04:33
  • You will need to go "via" a class; `if let control = button as? UIControl { let accessIden = control as? UIAccessibilityIdentification }` – Paulw11 Jan 08 '19 at 04:40
  • Related - https://stackoverflow.com/questions/42033735/failing-cast-in-swift-from-any-to-protocol – Paulw11 Jan 08 '19 at 04:53

1 Answers1

1

You can check the list of UI elements here that conforms to UIAccessibilityIdentification.

As cast from Any to UIAccessibilityIdentification protocol is failed due to this bug in Swift so you first need to downcast to a known type that falls in the above list to cast as UIAccessibilityIdentification. For a UIButton, you can do it as below,

let b: Any = UIButton(frame: CGRect.zero)
if let button = b as? UIButton, let acc = button as? UIAccessibilityIdentification  {
    print("Its a button")
}
Kamran
  • 14,987
  • 4
  • 33
  • 51
  • Did you try `class ProtoCheck: NSObject, UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } } let check: Any = ProtoCheck() let checkDelegate = check as? UITableViewDelegate`. Any doesn't conform to `UITableViewDelegate` either, but in this case it works. So the reason you have provided in your answer is not correct. – Midhun MP Jan 08 '19 at 05:46
  • 1
    @MidhunMP. You can check the `Swift` issue [here](https://bugs.swift.org/browse/SR-3871). In your example, the runtime is able to cast to `ProtoCheck` as probably it first tries to cast any as `AnyObject` and then ProtoCheck(check->AnyObject->ProtoCheck). In OP's case, it tries to cast any to protocol without trying the bridged type and fails. – Kamran Jan 08 '19 at 06:14
  • 1
    I understand the issue, I'm concerned about this line `As Any is not in the list so you first need to downcast to a know type` in your answer, because it doesn't make any sense. The issue is related to class, structs & any type. – Midhun MP Jan 08 '19 at 06:18