Search code examples
iosswiftenumsdirectoryuipageviewcontroller

Where to place view controller related enum


Situation

I have a Page View Controller with number of child view controllers. Each one of the child view controllers are slightly different.

To make it easy to manage, I defined enum MyPageViewChild

enum MyPageViewChild {
    case someName...
    case someName...
    case someName...
    case someName...
    case someName...
    case someName...
    case someName...
}


Problem

I'm struggling to figure out where is the best file to place the enum.

When the enum is short(like with no additional var & funcs other that case declaration), I would probably be ok to place it in the same file as the Page View Controller.

When the enum was quite long, like having many additional var & funcs, it should be places somewhere but not inside the same file as the Page View Controller.


Question

It is strongly related to view controllers so I plan to create a file PageViewChild.swift and place it in same directly as the Page View Controller.

So the directory(or actually Xcode group) would be like this.

- ViewController
    - MyPageViewChild.swlft <- enum among with view controllers
    - MyPageViewController.swift
    - MyPageViewChildOne
    - MyPageViewChildTwo
    - MyPageViewChildThree

Would the example above is ok or it should be places somere like under model directory or enums directory inside the project?


Solution

  • First of all, I have to say that is opinion-based question, it really depends on your code organization.

    Anyway, there is no difference if you declare enum in class scope or outside of the scope. The only thing you have to keep in mind is that if you need to get reference for it, you have to specify where enum is declared

    SomeClass.Enum
    

    I think, if enum is strongly related with some other class, it's fine to declare enum inside scope of related class. This behaviour we can see for example in new versions of Swift where lot of enums has been renamed (basically, enum’s been moved to related class’s scope and renamed to clever self-describing shorter name)

    Good example can be renaming enum for events related with UIControl

    UIControlEvents -> UIControl.Event
    

    So do you see that strategy? So, decide.