Highly intelligent iOS developers use enum with properties. Don’t make your code seem dull.
I learned C, C++, Java, Kotlin, Typescript and many other languages. I’m pretty sure swift’s enum is the best. If you use enum and protocols, you can write really easy-to-understand and a small amount of codes. I praise the swift enum.
There are many features for enum itself, But in this article, I will show you only one useful feature. “Enum Properties”
Define Enum and its properties
You might understand the power of enum properties or not. But I will show you the practical example.
Using with CaseIterable
Now, Menu
conforms to CaseIterable.
As a result, we can use this syntax.
let menus: [Menu] = [.coffee, .bread]
If I had defined Menu
with struct, it would have been more verbose.
let menus: [Menu] = [Menu(title: "Coffee", price: 6.5, origin: "Ethiophia", calories: 5.0), Menu(title: "Bread", price: 3.5, origin: "Ukraine", calories: 120)]
My another usecase
The images above are from my recent project. As you can see, those two dialogs have the same structure. Title-Image-Button. just different title and image. So, I decided to use enum properties.
MySomeDialogView(type: .charge)
Yeah! It is that simple! By just adding enum values and its title and image, you can be able to respond flexibly.
Conclusion
Working as an iOS Developer, I’m loving enum more and more. It’s just one feature that I introduced you. But there are many more features that make your life easier! Just remember that “you can add properties to enum”!