Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make a smart and dynamic initialization depending on first choice on init in Swift?

I want define a smart initialization method that it understands the chosen first parameter and adjust itself for it!

Here is my code:

struct Test {

    enum Kind { case vertical, horizontal }
    enum VerticalAlignment { case top, center, bottom }
    enum HorizontalAlignment { case leading, center, trailing }
    
    
    // if kind == horizontal then just VerticalAlignment:
    init(kind: Kind, verticalAlignment: VerticalAlignment) {
        
    }
    
    // if kind == vertical then just HorizontalAlignment:
    init(kind: Kind, horizontalAlignment: HorizontalAlignment) {
        
    }
    
}

As you can see in my codes, I have an initialization parameter called kind, here would be logic, if i chose .vertical then I want my second parameter automatically adjust itself to HorizontalAlignment type!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue with my code is that we can chose .horizontal and also get HorizontalAlignment type for second parameter!

I want limit my initialization and make it mistake-proof initialization,
my goal is JUST this 2 initialization way:

. vertical → HorizontalAlignment

. horizontal → VerticalAlignment


How can I have both parameters available for initialization with those limitation?

>Solution :

struct Test {
    
    enum VerticalAlignment { case top, center, bottom }
    enum HorizontalAlignment { case leading, center, trailing }

    enum Kind { case vertical(VerticalAlignment),
                     horizontal(HorizontalAlignment) }
    
    init(kind: Kind) {
        switch kind {
        case .horizontal(let horizontalAlignment):
            switch horizontalAlignment {
            case .center:
                ...
            }
        case .vertical(let verticalAlignment):
            ...
        }
    }
    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading