Hadi Sharghi
Hadi Sharghi

Reputation: 1005

Dynamic type casting in swift 4

I've got a class named Filters

class Filters {

   typealias States = [State]
   typealias Cities = [City]
   typealias Areas = [Area]

   var states : States?
   var cities : Cities?
   var areas : Areas?
}

In a FilterViewController, based on user's selection, pickerViewItems will be populated with items of filters.states, filters.cities or filters.areas.

The problem is when I populate the pickerViewItems with one of the three array item, e.g. filters.states, I can't cast it to States so I will be able to use

pickerViewItems[row].name

Value of type 'Any' has no member 'name'

How can I set the type of pickerViewItems dynamically in Swift?

Upvotes: 1

Views: 858

Answers (1)

Sweeper
Sweeper

Reputation: 274835

Swift is pretty much a static language so you can't dynamically change the type. Therefore, we are going to use polymorphism to work around this.

Assuming that State, City and Area all have a name property, you can create an protocol like this:

protocol NamedLocation {
    var name: String { get; }
}

And make all three classes conform to the protocol:

extension State: NamedLocation { }
extension City: NamedLocation { }
extension Area: NamedLocation { }

Now you can make your pickerViewItems to be of type [NamedLocation] and you can still access the name property.

Upvotes: 2

Related Questions