Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum in a class in Swift

Tags:

enums

swift

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'
like image 257
user3561494 Avatar asked Nov 27 '14 16:11

user3561494


People also ask

Can I declare enum inside a class?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

How do I enum in Swift?

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.

Can an enum have a function Swift?

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.

What is difference between enum and enumeration in Swift?

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.


1 Answers

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
like image 186
Antonio Avatar answered Oct 19 '22 07:10

Antonio