Enums with associated values in swift
Enums with associated values
Enums are a collection of distinct values that some how belong together.
An example of an enum would be
enum Gender { case male
case female
case others }Here use can see that the enum gender is a collection of genders. For most cases these kind of simple enums would suffice. But for complex cases this wont suffice. Lets look into a example, lets make a enum for celestial bodies
The enum celestial bodies does not hold any additional info about the cases. Lets alter it a bit.enum CelestialBodies {case starcase blackHolescase cometscase astroidscase planet }
1. Add size attribute to star
2. Add info comet to check if pose any threat to earth and its closest distance to earth
3. Add info to planet whether it can support life
enum
CelestialBodies {
case star(size:Int)
case blackHoles
case comets(threartToEarth:Bool, closestDistanceToEarth:Double)
case astroids
case planet(canSupportLife:Bool)
}
var celentialBodyComet = CelestialBodies.comets(threartToEarth: false, closestDistanceToEarth: 954000)
switch celentialBodyComet {case .star(size: let size):
print(size)
case .blackHoles:
print("Black hole")
case .comets(threartToEarth: let threartToEarth, closestDistanceToEarth: let closestDistanceToEarth):
print("Its a comet")
print("At a distance of \(closestDistanceToEarth) its a threat \(threartToEarth)")
case .astroids:
print("astroids")
case .planet(canSupportLife: let canSupportLife):
print("Planet car support life : \(canSupportLife)")}
Comments
Post a Comment