Mark Löwe
Mark Löwe

Reputation: 582

Swift: Checking Object Type In Loop

I'm trying to check the type of an object that can be various structs inside a for loop, but I'm getting errors on two sides. Here's my code:

for object in objectArray {

    if object is structType
    {
      ....
    }
}

The error I'm getting is on the is in the if statement. The compiler is saying that the is condition will always evaluate as true. Why?

If I use the object: Any technique in the for loop, then any sub check within the if complains that the Any declaration refuses me to check things like object.name claiming the object can't have sub properties such as name.

My code is sending a random struct type to a function to be processed, and based on the discovered type, I need to drill down into that object for different properties.

Is there a better way to do this?

Upvotes: 0

Views: 123

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59496

It depends on the definition of objectArray.

If objectArray is defined as an Array of a given Struct (let's say something like this [Cat]) and then you check whether an element is a Cat, of course the compiler will tell you that it is always true.

Maybe you want something like this

struct Cat { }
struct Dog { }
struct Lion { }

let animals:[Any] = [Cat(), Dog(), Lion()]

for animal in animals {
    switch animal {
    case let cat as Cat: print("It's a cat")
    case let dog as Dog: print("It's a dog")
    case let lion as Lion: print("It's a lion")
    default: fatalError()
    }
}

Upvotes: 1

Quantaliinuxite
Quantaliinuxite

Reputation: 3223

The error I'm getting is on the is in the if statement. The compiler is saying that the is condition will always evaluate as true. Why?

This means the object type of your objectArray is structType. Otherwise this is a bug in xCode (it's happened to me).

If I use the object: Any technique in the for loop, then any sub check within the if complains that the Any declaration refuses me to check things like object.name claiming the object can't have sub properties such as name.

You first need to cast the object to the structType before you can access the methods, otherwise the compiler won't know it owns the properties. As @mattias suggested, I would do

if let myStruct = object as? structType {
    print("\(myStruct.name)")
} 

Also if you have many of those structs (say more than 2) and they have similar properties, i would recommend you use protocols to avoid a massive list of if lets

Upvotes: 2

Related Questions