Ian
Ian

Reputation: 239

the function to call all subClasses from superClass

I guess this is an easy one but I've been searching for hours and still can't figure out what function do I call to do this.

so say I have one super class country and three subclasses like this

class country {
}

class USA : country {
}
class China : country {
}
class France : country {
}
var countrys : [country] = []

and I now want to push all subclasses into an array of country class

what do I call in append function??

countrys.append(contentsOf:  )

any hints are appreciated ! :D

Upvotes: 0

Views: 152

Answers (2)

Price Ringo
Price Ringo

Reputation: 3440

No Objective C is required, desired, or needed. In the most minimal way possible, you can create your Country arrays like this depending on whether they need to be read-only or read-write.

class Country {}

class USA: Country {}
class China: Country {}
class France: Country {}

var countries = [Country]()
countries.append(USA())
countries.append(China())
countries.append(France())

let moreCountries = [France(), China(), USA()]

However, creating individual subtypes for each possible country is a misuse of the type system at face value. Here is an alternate answer in a more idiomatic way. But this is a design question and is dependent on details not provided.

class Country {
   let name: String
}

var countries = [Country]()
countries.append(Country(name: "USA"))
countries.append(Country(name: "China"))
countries.append(Country(name: "France"))

let moreCountries = [Country(name: "France"), Country(name: "China"), Country(name: "USA"))

let usa = Country(name: "USA")
let china = Country(name: "China")
let france = Country(name: "France")
let evenMoreCountries = [china, france, usa]

Upvotes: 1

Gary Makin
Gary Makin

Reputation: 3169

What you would like to do is possible in Objective-C, using introspection, and in C++, using static code that gets run at the very start of the program. However, it is not possible in Swift.

While you can't get something that happens automatically, a manual approach will work.

Define your classes something like:

class Country {
    static var countries = [Country.Type]()
    static func addMe() { Country.countries.append(self) }
}

class USA : Country {
}
class China : Country {
}
class France : Country {
}

and in some initialisation code call:

USA.addMe()
France.addMe()
China.addMe()

then calling print("Country.countries \(Country.countries)") will give you:

Country.countries [Module.USA, Module.France, Module.China]

If this really needs to be done automatically, look into what you could do in Objective-C and have Country be a subclass of NSObject.

Upvotes: 2

Related Questions