将TypeA的通用实例视为SuperclassOfTypeA的通用实例

时间:2014-07-09 02:09:33

标签: ios swift

假设我有一个var responders = [String:[UIResponder]]()(读作:DictionaryString为键,ArrayUIResponder s为值。

我可以将[String:[UIView]]视为[String:[UIResponder]]吗?

UIView转换为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'

甚至更奇怪的是,只使用[UIResponder](读取:Array UIResponders)就可以了。

import UIKit

var responders = [UIResponder]()

var views = [UIView]()

responders = views // No error

responders = views as [UIResponder] // No error

感谢您的帮助! :)

1 个答案:

答案 0 :(得分:1)

您可以使用reinterpretCast强制演员:

import UIKit

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

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

responders = reinterpretCast(views)

虽然通过这样做,您承担了确保演员表有效的责任。