Tuesday, August 28, 2018

Enum raw value comparisons


It’s a good practice to take an enum for TableView sections instead of writing if conditions for indexPath.section


     
  if section == 0 {} 

  if section == 1 {} 



Instead of this take an enum like below for example as a Profile screen.


     
 enum ProfileSections: Int {
    case Profile = 0,
    Info,
    Friends
 }



Now, usually what we do is like below,


     
 if section == ProfileSections.Profile.rawValue 
  {print("Profile Section")}

 if section == ProfileSections.Info.rawValue 
  {print("Info Section")}

 if section == ProfileSections.Friends.rawValue    
  {print("Friends Section")}



If we write like this, there is no point of taking an enum. Because It’s same like,


     
 if indexPath.section == 0 {} 

 if indexPath.section == 1 {} 



Agree?

The better approach would be below.


     
 let section = 2

 if let profileSection = ProfileSections(rawValue: section) {

    switch profileSection {

    case .Profile:
        print("Profile Section")

    case .Info:
        print("Info Section")

    case .Friends:
        print("Friends Section")

    }

 }



Convert the section to ProfileSections and write a switch case.

Incase you will need to add a new section like Bio, It’s as simple as adding another switch case.

     
 enum ProfileSections: Int {
    case Profile = 0,
    Info,
    Bio,
    Friends
 }

 if let profileSection = ProfileSections(rawValue: section) {

    switch profileSection {

    case .Profile:
        print("Profile Section")

    case .Info:
        print("Info Section")

    case .Friends:
        print("Friends Section")

    case .Bio:
        print("Bio Section")

    }

 }



The beauty here, with switch, we get a build error for missing case :)


     
 // note: add missing case: '.Bio'
    switch profileSection {
    ^



Hope this post is useful. Feel free to comment incase of any queries.



No comments:

Post a Comment