norq
norq

Reputation: 1434

Undeclared type in enum while the declaration is in the same file

I'm trying to make a simple data type for storing video or image + sound but i get a compilation error "Use of undeclared type" on the enum MovieItem and ImageItem. What is wrong?

struct MovieItem {
    let movieUrl: NSURL
}

struct ImageItem {
    let imageUrl: NSURL // UIImage?
    let soundUrl: NSURL
}

enum Item {
    case MovieItem(MovieItem) // Undeclared type: MovieItem
    case ImageItem(ImageItem) // Undeclared type: ImageItem
}

Upvotes: 2

Views: 2116

Answers (3)

DiogoNeves
DiogoNeves

Reputation: 1777

You could declare a typealias (outside the enum) with different type names. It results in a more obscure and confusing code in this case, but I left it here just to consider other options:

struct MovieItem {
    let movieUrl: NSURL
}

struct ImageItem {
    let imageUrl: NSURL // UIImage?
    let soundUrl: NSURL
}

typealias MovieItemType = MovieItem
typealias ImageItemType = ImageItem

enum Item {
    case MovieItem(MovieItemType)
    case ImageItem(ImageItemType)
}

Upvotes: 0

Stefan Salatic
Stefan Salatic

Reputation: 4523

It appears that my old answer was bad. Roman has the right answer.

I'm updating it so it is correct now.

This doesn't produce an error

struct MovieItem {
    let movieUrl: NSURL
}

struct ImageItem {
    let imageUrl: NSURL // UIImage?
    let soundUrl: NSURL
}

enum Item {
    case Movie(MovieItem) 
    case Image(ImageItem) 
}

Upvotes: 0

Aaron Rasmussen
Aaron Rasmussen

Reputation: 13316

I think the compiler is confused by your use of MovieItem as the name of a struct and by its use as a case label inside of Item. If you change the name of the case label it should work:

struct MovieItem {
    let movieUrl: NSURL
}

struct ImageItem {
    let imageUrl: NSURL // UIImage?
    let soundUrl: NSURL
}

// Changed MovieItem to Movie and ImageItem to Image and it works
enum Item {
    case Movie(MovieItem)
    case Image(ImageItem)
}

Upvotes: 8

Related Questions