Generic type casting for anyone?

I have a class called Box with the generics T parameter.

For some reason, it is not valid in Swift to use a Box<String> (or any other type, for that matter) before Box<Any> .

 class Box<T> {} var box: Box<Any>? box = Box<String>() // 'String' is not identical to 'Any' 

Is there any in Java ? that represents any type. ( Box<?> )

What can I do here in Swift?

+2
source share
2 answers

Short answer: you cannot distinguish Box<String> to Box<Any> because there is no relationship between them.

This page is for Java, but it also applies here.

Given the two specific types A and B (for example, a number and an integer), MyClass <A> is not related to MyClass <B>, regardless of whether A and B are connected or not. The common parent element is MyClass <A> and MyClass <B> Object.

Unless you explicitly define a relationship. for example, support an 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>() } } 
+7
source

First, why do you want your box variable to be of type Box<Any> but contain an instance of Box<String> ?

Swift is a type-safe language; you cannot assign an object to a variable that is not of the same type. It is 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, simply declare it as follows:

 var box = Box<AnyObject>? 

And you will have a box instance that I think you need.

See this security type link 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 is when using 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,

+1
source

Source: https://habr.com/ru/post/974062/


All Articles