I'm currently porting an iOS app from Objective-C to Swift. While doing that I just stumbled across a problem I'm struggling with.
I have a variable ("value") which can bet set to AnyObject?, especially can it be of type String, Array, Dictionary and Set. Now, in my previous code I was testing my "value" variable for its value's type in order to further work with it:
id value = [myDatahandler getValue];
if (([value isKindOfClass:[NSSet class]] || [value isKindOfClass:[NSArray class]]) && [value count] > 0) {
// do something
}
Trying to do the same in Swift seems not to work...
var value: AnyObject? = myDatahandler.getValue()
if (value is Set || value is Array) && value!.count > 0 {
// Error:
// Generic parameter 'Element' could not be inferred in cast to 'Array'
// Generic parameter 'Element' could not be inferred in cast to 'Set'
}
After a couple of hours searching for the right way to do this but not finding anything helpful, I hope the community can come to my rescue here...
Any suggestions how this could work?
I feel like you can use a guard to do this.. Hope the following piece of code works.