Doug Smith
Doug Smith

Reputation: 29316

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

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?

Upvotes: 21

Views: 20546

Answers (2)

Connor
Connor

Reputation: 64644

You can't use the default value of one property in the default value of another. You can fix this by setting color in the init method:

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

Since Color is an enum inside of ClassOne, for its type you should use ClassOne.Color instead of Color.

You could also make color a computed property like this:

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

In the first example color is set as classOne.giveColor() only when it is initialized, but in the second example classOne.giveColor() is called everytime you try to access color.

Upvotes: 3

Nate Cook
Nate Cook

Reputation: 93276

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()
    }
}

Upvotes: 33

Related Questions