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 DogDetailModel
s, CatDetailModel
s and AnimalDetailModel
s 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?
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.
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.)
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With