This syntax of defining enum with associated values used to work fine with Swift 4.2
enum NetworkService {
case lookUp(type: String)
case allLookUps()
}
When I am trying to convert my code in Xcode 10.2 and Swift 5, it is throwing error saying
Enum element with associated values must have at least one associated value
It doesn't make any sense in this particular case to have associated value for allLookUps(). So what is the best practice here in Swift 5?
In Swift enum, we learned how to define a data type that has a fixed set of related values. However, sometimes we may want to attach additional information to enum values. These additional information attached to enum values are called associated values.
The raw value for a particular enumeration case is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration's cases, and can be different each time you do so.
Each raw value for our enum case must be a unique string, character, or value of any integer or floating-point type. This means the value for the two case statements cannot be the same.
These additional information attached to enum values are called associated values. enum Distance { // associate value case km (String) ... } Here, (String) is additional information attached to the value km. It represents that the value of km can only be a String. Now, here's how we assign the associated value to the enum value.
By defining a finite set of values, the enum is more type safe than constant literal variables like String or int. However, enum values are required to be valid identifiers, and we're encouraged to use SCREAMING_SNAKE_CASE by convention.
The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type-safe than constant literal variables like String or int. However, enum values are required to be valid identifiers, and we’re encouraged to use SCREAMING_SNAKE_CASE by convention.
Since the value matches with case let .suv, the statement inside the case is executed. In Swift, raw values are predefined constant values provided to each enum value. For example, Here, we have provided the raw values: "Four Wheeler" and "Two Wheeler" to car and bike respectively.
Simply remove the brackets () after the case:
enum NetworkService {
case lookUp(type: String)
case allLookUps
}
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