1

I'm getting this strange behavior with struct in swift. I have the following code and getting error:

Constant 'self.b' captured by a closure before being initialized

struct Test {
    let a = 10
    let b: Int

    init(_ x: Int, y: Int) {
        if x < y && y == a {
            b = x
        } else {
            b = 0
        }
    }
}

But if I use the following code it compiles fine:

struct Test {
    let a = 10
    let b: Int

    init(_ x: Int, y: Int) {
        if y == a {
            b = x
        } else {
            b = 0
        }
    }
}

Or even this code compiles fine:

struct Test {
    let a = 10
    let b: Int

    init(_ x: Int, y: Int) {
        if x < y {
            if y == a {
                b = x
            } else {
                b = 0
            }
        } else {
            b = 0
        }
    }
}

Update: I tried it with guard statement and it works fine with that

struct Test {
    let a = 10
    let b: Int

    init(_ x: Int, y: Int) {
        guard x < y, y == a else {
            b = 0
            return
        }

        b = x
    }
}
Mukesh
  • 2,792
  • 15
  • 32
  • As in the linked-to Q&A, the error is caused by the auto closure of the second argument of the short-circuiting operator `&&`. Inserting `let a = self.a` before the if-statement would be one way to solve the problem, or rewriting the if-statement as `if x < y, y == a { ... }` – Martin R Jan 27 '19 at 16:47
  • @MartinR so `&&` operator usage auto closure but `,` operator doesn't? – Mukesh Jan 27 '19 at 16:49
  • `,` is not an operator but part of the [condition-list](https://docs.swift.org/swift-book/ReferenceManual/Statements.html#grammar_condition-list) in the if-statement. As far as I know, it is just a shortcut for a nested if-statement. – Martin R Jan 27 '19 at 16:52
  • @MartinR Man, that's a pretty serious language design flaw. Have you seen any discussions in Swift Evolution about it? – Alexander Jan 27 '19 at 16:58
  • @Alexander: https://forums.swift.org/t/autoclosure-of-self-in-initializers/13651, https://bugs.swift.org/browse/SR-944. – Martin R Jan 27 '19 at 17:01

0 Answers0