Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of objects that have specific type

Tags:

arrays

swift

I have an array of object, eg

var objects: [AnimalDetailModel] = ...

and also three classes

  • AnimalDetailModel is a base class

  • DogDetailModel is a class that extends AnimalDetailModel

  • CatDetailModel is a class that extends AnimalDetailModel

From a datasource I create and add arrays of DogDetailModels, CatDetailModels and AnimalDetailModels to objects. And when populating the tableView what I want is to get an object form objects and check if it is of type DogDetailModel, CatDetailModel or AnimalDetailModel like

if let objects[indexPath.row] as? DogDetailModel {    
    return DogTableCell    
} else if let objects[indexPath.row] as? CatDetailModel {    
    return CatTableCell     
} else {    
    return AnimalTableCell    
}

While doing this I get type AnimalDetailModel has no subscript members. How do we check the type of objects from array of objects?

like image 594
SarojMjn Avatar asked Jul 22 '19 06:07

SarojMjn


People also ask

What is the type of array of objects?

An array of Objects is used to store a fixed-size sequential collection of elements of the same type. TypeScript Arrays are themselves a data type just like a string, Boolean, and number, we know that there are a lot of ways to declare the arrays in TypeScript.

How do you find a specific object in an array of objects?

If you need the index of the found element in the array, use findIndex() . If you need to find the index of a value, use Array.prototype.indexOf() . (It's similar to findIndex() , but checks each element for equality with the value instead of using a testing function.)

How do I find a specific item in an array?

To find if an array contains an element in a JavaScript array, use the array includes() method. Javascript includes() is a built-in array function that determines whether an array contains the specified element. It returns true if it consists of an element, otherwise false, without including the element in the array.

How do I find unique objects in an array?

One way to get distinct values from an array of JavaScript objects is to use the array's map method to get an array with the values of a property in each object. Then we can remove the duplicate values with the Set constructor. And then we can convert the set back to an array with the spread operator.


1 Answers

You can use the short and simple is attribute.

which in your case will be:

switch objects[indexPath.row] {
    case is DogDetailModel:
        return DogTableCell
    case is CatDetailModel:
        return CatTableCell
    default:
        return AnimalTableCell
}
like image 170
Vollan Avatar answered Sep 30 '22 17:09

Vollan