Enum is a powerful and useful tool in Swift. In this post, I want to present a use case of enum in SwiftUI ActionSheet selection.
Let say that in the app that we are developing, we allow the user to choose different language in the settings page. Here is how the action sheet might look like with the use of action sheet:
The basic approach to this problem is to use the following code for the action sheet, in which we are specifying every single options ourselves manually.
.actionSheet(isPresented: $showingSelectLanguageSetting) {
ActionSheet(title: Text("Language"), message: Text("Please select your prefered language"), buttons:[
.default(Text("English")) {}, //some action
.default(Text("Chinese")) {}, //some action
]
)
}
If the number of options are very little and the actions needed for each option is simple, this approach is perfectly fine. However, if we are required to add more actions and options in the future, the code might get more complicated and this might not be the cleanest approach.
For example, lets imagine that we want to support 5 languages, and that with selection of each language, we want to set the language code variable into their respective language code:
.actionSheet(isPresented: $showingSelectLanguageSetting) {
ActionSheet(title: Text("Language"), message: Text("Please select your prefered language"), buttons:[
.default(Text("English")) {self.languageCode = "en"}, //some action
.default(Text("Chinese")) {self.languageCode = "zn"}, //some action
.default(Text("German")) {self.languageCode = "de"}, //some action
.default(Text("Indonesian")) {self.languageCode = "id"}, //some action
.default(Text("Latin")) {self.languageCode = "la"}, //some action
]
)
}
Things can easily get messier with every new action or options being added to the action sheet.
To easily solve this problem, we can make use of enum. First we can define an Enum called Language and specify all the languages in the Enum.
enum Language : String , CaseIterable {
case english = "English"
case mandarin = "Chinese"
func getLanguageCode()->String{
switch self {
case .english:
return "en"
case .mandarin:
return "zn"
}
}
}
Next, we can define our action sheet as such:
.actionSheet(isPresented: $showingSelectLanguageSetting) {
ActionSheet(title: Text("Language"), message: Text("Please select your prefered language"), buttons:
Language.allCases.map{language in
Alert.Button.default(Text(language.rawValue)) {
self.languageCode = language.getLanguageCode() //assign the language code
}
}
)
}
With the use of CaseIterable with Enum, we can separate the language related logic from the UI related logic, making our code more readable and maintainable in future.
Top comments (0)