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
}
}