Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an enum from another class in Swift?

Tags:

Say I have the following example:

class ClassOne {
    enum Color {
        case Red
        case Blue
    }

    func giveColor() -> Color {
        return .Red
    }
}

class ClassTwo {
    let classOne = ClassOne()
    var color: Color = classOne.giveColor()
}

The compiler complains that it doesn't know what Color is in ClassTwo. How would I best handle this?

like image 347
Doug Smith Avatar asked Jun 28 '14 01:06

Doug Smith


People also ask

How do you find the enum in a class?

Every enum constant is always implicitly public static final. Since it is static, we can access it by using the enum Name. Since it is final, we can't create child enums. We can declare the main() method inside the enum.

Can enum be inherited Swift?

In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.

How does enum work in Swift?

Enumerations (or enums for short) in Swift define a common type for a group of related values. According to the Swift documentation, enums enable you to work with those values in a type-safe way within your code. Enums come in particularly handy when you have a lot of different options you want to encode.

How do I enum in Swift?

In Swift, we can also assign values to each enum case. For example, enum Size : Int { case small = 10 case medium = 12 ... } Here, we have assigned values 29 and 31 to enum cases small and medium respectively.


1 Answers

Your Color enumeration is a nested type -- you'll access it as ClassOne.Color. Moreover, you can't assign one property from another in the declaration like that. Leave it unassigned and do it in the init():

class ClassOne {
    enum Color {
        case Red
        case Blue
    }

    func giveColor() -> Color {
        return .Red
    }
}

class ClassTwo {
    let classOne = ClassOne()
    var color: ClassOne.Color

    init() {
        self.color = self.classOne.giveColor()
    }
}
like image 72
Nate Cook Avatar answered Sep 17 '22 07:09

Nate Cook