Reputation: 6852
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?
Upvotes: 2
Views: 2240
Reputation: 46578
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
Given two concrete types A and B (for example, Number and Integer), MyClass<A> has no relationship to MyClass<B>, regardless of whether or not A and B are related. The common parent of MyClass<A> and MyClass<B> is Object.
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>()
}
}
Upvotes: 7
Reputation: 2559
First, why would you want your box
variable to be of type Box<Any>
but to contain an instance of Box<String>
?
Swift being a type-safe language, you cannot assign to a variable an object that is not of the same type. It's as simple as you cannot do this:
var x: Float
x = 2 as Int
If you want your Box
instance to be associated with any object of any class, just declare it like that:
var box = Box<AnyObject>?
And you will have the box
instance that I guess you need.
See this link on type safety in Swift: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_443
And this one on the use of Any
and AnyObject
: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html#//apple_ref/doc/uid/TP40014097-CH22-XID_492
Hope this helps,
Upvotes: 1