Home > Mobile >  Swift: Is it possible to conditionally declare variables?
Swift: Is it possible to conditionally declare variables?

Time:10-05

Let's say there is a struct with two variables: a and b.

It is possible to declare one of the two variables and ignore the other based on a condition?

In other words, is it possible from this struct:

struct example {
    let a: Int
    let b: Int
}

To do this:

struct example {
    if (condition) {
        let a: Int
    } else {
        let b: Int
    }
}

CodePudding user response:

This is not possible, because if you did this, what would this code do:

let e = exampleReturningFunction()
print(e.a)

If condition is false, should this crash? Should a have some default value? What value? (If so, just use a default value in the struct.)

In most cases, what you really want here is an enum with associated data:

enum Example {
    case a(Int)
    case b(Int)
}

If there are many related properties, you can group them together:

struct A { ... }
struct B { ... }

enum Example {
    case a(A)
    case b(B)
}
  • Related