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

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

Conclusion

In this Swift Tutorial, we learned how to solve the Swift Compiler Error “Variable used before being initialized”.