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!
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):
...
}
}
}