Swift – Variable used before being initialized
Before we can use a variable in Swift, the variable has to be initialised. There is no default value assigned to a variable when we declare it.
For example, let us declare a variable x
to type Int, and print its value, without any initialisation done to x
.
main.swift
![Swift - Variable used before being initialized](https://www.tutorialkart.com/wp-content/uploads/2021/05/swift-variable-used-before-being-initialized-1.png)
ADVERTISEMENT
If we initialize the variable x with some value, then we can use the variable in the rest of the program.
main.swift
![Swift - Variable used before being initialized](https://www.tutorialkart.com/wp-content/uploads/2021/05/swift-variable-used-before-being-initialized-solved.png)
Conclusion
In this Swift Tutorial, we learned how to solve the Swift Compiler Error “Variable used before being initialized”.