I am creating a single structure in Swift that has a measuring superclass and subclasses for different units such as mass and volume. The peculiarity is to allow the framework to correctly guess which block it was created from and return the correct class. code example:
class Measurement { var unitString : String init(unknownUnit: String) { // checks if the unit is either Volume or Mass, and returns an instance of that class } } class Volume : Measurement { init(unitString: String) { } } class Mass : Measurement { init(unitString: String) { } } let mass = Mass("kg") // class: Mass let volume = Volume("ml") // class: Volume let shouldBeVolume = Measurement("ml") // class: Volume let shouldBeMass = Measurement("kg") // class: Mass
Is it possible for an inherited class to create an object of a particular subclass when it is initialized?
The library is called Indus Valley and is open source on GitHub
source share