Fast generic type

I have a generic class where I have an array of generic types. No. I want to perform some operations based on a class in an array. I have 2 classes: Person and House (without inheritance). But this code does not work:

let allValues = [T]() if allValues[0] is Person { let values = (allValues as [Person]) } 

But this does not work, since T is not identical to "Personality". What do I need to do? Thanks for any help.

+4
source share
2 answers

I agree with Oliver Borchert and Airspeed speed : this problem should be resolved using a protocol.

However, you can complete the cast you asked for using this syntax:

 let values = allValues as Any as [Person] 

Now I see 2 problems:

  • Your IF will fail because your allValues array contains 0 elements, and you get access to the first (this does not exist).
  • allValues ​​may have Person in the first element and something else in the second position. This makes coercion dangerous after evaluating only the first element.

    Example

    class LifeForm {}

    class Person: LifeForm {}

    With T equals LifeForm.

I think the next version is safer because you directly evaluate type T.

 class Things<T>{ func doSomething() { let allValues = [T]() // populate allValues.... if T.self is Person.Type { println("List of Person") let values = allValues as Any as [Person] } } } 

Important: I provided this code to show the syntax. I don’t like this abborder (again, the protocol will be better), because the Things class contains entity-specific logic. Ideally, Things should not know anything about Person , because Things are a common class.

+2
source

You cannot do this (or at least not jump over some rather winding and impractical hoops). You think of T more as an Any type, which is a type that any other type can contain, and that you can return to a real type with as (or probably preferably as? ) At runtime.

But generics don't work like that. In your code, the generic T will be replaced with the actual type at compile time, and this type may not be Person . What would the code do if it were?

What is the main functionality that you are actually trying to achieve? People and homes are very different, so do you really need to write a function that works in general on both of them?

+3
source

All Articles