I have the following Swift enum:
enum ScreenName: String {
case start = "Start Screen"
case dashboard = "My Dashboard Screen"
}
Which allows me to have a typed set of constants and use them like:
func trackView(screen: ScreenName) {
print("viewed \(screen.rawValue)")
}
trackView(screen: .start) // -> "viewed Start Screen"
What would be the equivalent of this in Kotlin?
Kotlin enums are classes, which means that they can have one or more constructors. Thus, you can initialize enum constants by passing the values required to one of the valid constructors. This is possible because enum constants are nothing other than instances of the enum class itself.
Cases as functions Finally, let's take a look at how enum cases relate to functions, and how Swift 5.3 brings a new feature that lets us combine protocols with enums in brand new ways. A really interesting aspect of enum cases with associated values is that they can actually be used directly as functions.
The name of an enum in Swift should follow the PascalCase naming convention in which the first letter of each word in a compound word is capitalized.
In Swift, an enum (short for enumeration) is a user-defined data type that has a fixed set of related values. We use the enum keyword to create an enum. For example, enum Season { case spring, summer, autumn, winter } Here, Season - name of the enum.
something like:
enum class ScreenName(val displayName : String) {
START("Start Screen"),
DASHBOARD("My Dashboard Screen")
}
fun trackView(screenName : ScreenName) {
print("viewed ${screenName.displayName}")
}
Another possibility which I have discovered now, is with a sealed class:
sealed class ScreenName(val name : String) {
object Start : ScreenName("Start Screen")
object Dashboard : ScreenName("My Dashboard Screen")
data class NewsDetail(val title: String) : ScreenName("News")
val displayName: String
get() = when(this) {
is NewsDetail -> "${name} - ${title}"
else -> name
}
}
This has the advantage that it can mimic Swift enums with associated values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With