Enums as Constants in Swift iOS, Easily parse with JSONDecoder & JSONEncoder - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

27 May 2019

Enums as Constants in Swift iOS, Easily parse with JSONDecoder & JSONEncoder

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.


Enums in swift, ios enums, what are enums in swift ios, Enumerations in swift 5, loop all cases in enums, json decoder and encoder for enums.Example of enums in swift, enums sample code swift

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 + Encodable

Enums 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"
        }
    }
}

No comments:

Post a Comment

Post Top Ad