How do you access a classes enum from outside of the class?
class Element
{
enum Type
{
case AUDIO
case LIGHT
case THERMOSTAT
}
}
var a = Element.Type.LIGHT // error: 'Element.Type.Type' does not have a member named 'LIGHT'
var b = Element.LIGHT // error: 'Element.Type' does not have a member named 'LIGHT'
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
To define an enum in Swift, use the keyword enum followed by the name of the enum. 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.
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.
Enumeration is a data type that allows you to define a list of possible values. An enum allows you to create a data type with those set of values so that they can be recognised consistently throughout your app.
A Type
property already exists (unlucky name :)), just rename it to something else, such as:
class Element
{
enum EnumType
{
case AUDIO
case LIGHT
case THERMOSTAT
}
}
var a = Element.EnumType.LIGHT
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