In olden languages like c, we can create enumerations with only integers. Swift allows to create enumerations in any type(int, string, Float) and easily create constants.
Enums can conform to protocols like Codable, CaseIterable.
Both are correct in swift, we can use based on our requirements.
Enums can confirm to Codable protocol so that we can use JSONDecoder & JSONEncoder to parse the json object easily.
Enums can conform to protocols like Codable, CaseIterable.
Basic Enum:
enum Beverage { case miller case kingfisher case corona case bira case budweiser }
Enum with Int:
enum Numbers: Int { case one = 1 case two = 2 case three = 3 case four = 4 case five = 5 } enum Numbers: Int { case one = 1, two, three, four1, five }
Both are correct in swift, we can use based on our requirements.
Enum conforms to CaseIterable:
enum Juices: CaseIterable { case orange case apple case mango case pomegranate var vitamin: String { switch self { case .orange: return "vitamin C" case .apple: return "vitamin C" case .mango: return "vitamin K" case .pomegranate: return "vitamin C & K" } } } let count = Juices.allCases.count print(count) // 4 let org = Juices.orange print(org.vitamin) // vitamin C
Enum conforms to Codable:
Codable = Decodable + EncodableEnums can confirm to Codable protocol so that we can use JSONDecoder & JSONEncoder to parse the json object easily.
enum Status: String, Codable { case waitingReview = "WATING" case inReview = "IN" case rejected = "REJECTED" case ready = "READY" var displayString: String { switch self { case .waitingReview: return "Waiting for review" case .inReview: return "In review" case .rejected: return "Rejected" case .ready: return "Ready for sale" } } }