问题描述
我有一个名为 Box
的类,其中泛型参数 T
。
由于某些原因,在Swift中将 Box< String>
(或任何其他类型)转换为 Box< Any>
。
class Box< T> {}
var box:Box< Any> ;?
box = Box< String>()//'String'与'Any'不一样
在Java中有一个代表任何类型的?
。 ( Box<>
)
在Swift中可以做什么? b
简短的回答是:您不可强制转换 Box< String>
Box< Any>
因为它们之间没有任何关系。
$ b 这个页面是用于Java的,但它也适用于这里
$ b
除非您明确定义关系。例如支持隐式转换操作符:
class Box< T> {
func __conversion< U>() - >盒及LT; U> {
//根据需要进行转换
//尝试reinterpretCast,如果无法使类型系统开心
//如果您做错了,会给您带来运行时错误...
return Box< U>()
}
}
I have a class called Box
with a generics parameter T
.
For some reason, it's not valid in Swift to cast a Box<String>
(or any other type, for that matter) to Box<Any>
.
class Box<T> {}
var box: Box<Any>?
box = Box<String>() // 'String' is not identical to 'Any'
In Java there is a ?
that represents any type. (Box<?>
)
What can I do here in Swift?
Short answer is: You cannot cast Box<String>
to Box<Any>
because there is no relationship between them.
This page is for Java, but it also apply here
Unless you explicit define a relationship. e.g. support implicit conversion operator:
class Box<T> {
func __conversion<U>() -> Box<U> {
// do whatever required for conversion
// try reinterpretCast if you can't make type system happy
// which will give you runtime error if you do it wrong...
return Box<U>()
}
}
这篇关于泛型类型转换为Any?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!