Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treat generic instance of TypeA as generic instance of SuperclassOfTypeA

Tags:

ios

swift

Let's say I have a var responders = [String:[UIResponder]]() (read: Dictionary with Strings as keys and Arrays of UIResponders as values).

Can I treat a [String:[UIView]] as if it's a [String:[UIResponder]]?

Wouldn't it be the same as casting a UIView to UIResponder?

import UIKit

var responders = [String:[UIResponder]]()

var views = [String:[UIView]]()

responders = views // Error: 'UIView' is not identical to 'UIResponder'

responders = views as [String:[UIResponder]] // Error: 'UIView' is not identical to 'UIResponder'

It's even weirder that using just an [UIResponder] (read: Array of UIResponders) works just fine.

import UIKit

var responders = [UIResponder]()

var views = [UIView]()

responders = views // No error

responders = views as [UIResponder] // No error

Thanks for any help! :)

like image 394
aleclarson Avatar asked Feb 03 '26 14:02

aleclarson


1 Answers

You could force the cast by using reinterpretCast:

import UIKit

var responders = [String:[UIResponder]]()

var views = [String:[UIView]]()

responders = reinterpretCast(views)

Although by doing this, you are taking on the responsibility of ensuring that the cast is valid.

like image 134
ColinE Avatar answered Feb 05 '26 04:02

ColinE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!