Monday 3 September 2018

Enum

Enum is data type for consisting name value like String, Int etc.
For good programer practice code is readable and reusable.
Enum is best for comparing in conditional statement and switch case.

For example if we match string type value like

func getDevice(forDeviceType deviceType : String){
    if deviceType == "iOS"{
        print("iOS")
    }else{
        print("Other device")
    }
}

Now how to use enum string type for above function 
enum enumDeviceType : String {
    case iOS
    case Android
}

func getDevice(forDeviceType deviceType : String){
    if deviceType == enumDeviceType.iOS.rawValue{
        print("iOS device")
    }else{
        print("Other device")
    }

}

another example of enums
enum myEnumList{
    case list1
    case list2
    
    var noOfItems : Int{
        switch self {
        case .list1:
            return 50
        case .list2:
            return 100
        }
    }
}

func listEnumTest(type : myEnumList)
{
    switch type {
    case .list1:
        print("hello list 1 total item is \(type.noOfItems)")
        break
    case .list2:
        print("hello list 2 total item is \(type.noOfItems)")
        break
    }
}

listEnumTest(type: .list1)

you can also watch video 




If you have any trouble in use of enum then pls comment 

Thank you


No comments:

Post a Comment