Blazey John
Blazey John

Reputation: 47

Swift variable used before initialised

If I write a code like this in swift it says variable x used before initialized. This seems legit in java. Why is this not possible in swift and how do I achieve the same?

  var x:Int
  var y:Int  = 0

  if (y==0) {
      x=0
   }

   if (y==1) {
      x=1
   }

   y=x

Upvotes: 2

Views: 1166

Answers (3)

vadian
vadian

Reputation: 285260

A non-optional variable cannot be used before being initialized. But it's possible to even use let when the variable is guaranteed to be initialized before using it

  let x: Int
  var y : Int = 0

  if (y==0) {
      x=0
   } else if (y==1) {
      x=1
   } else {
      x=2
   }

   y=x

Upvotes: 1

Ashish Kakkad
Ashish Kakkad

Reputation: 23892

You can use ! or ? to define variable without initializing

    var x:Int?
    var y:Int  = 0

    if (y==0) {
        x=0
    }

    if (y==1) {
        x=1
    }

    y=x!

OR

    var x:Int!
    var y:Int  = 0

    if (y==0) {
        x=0
    }

    if (y==1) {
        x=1
    }

    y=x

Upvotes: 1

Özgür Ersil
Özgür Ersil

Reputation: 7013

To use variables, it is an issue that you have to init them or you can force the variable with ! to unwrap or you can init it with optional by using ?. In this case you can use it like that

  var x:Int!  /// var x:Int?
  var y:Int  = 0

   if (y == 0) {
      x=0
   }

   if (y == 1) {
      x=1
   }

Upvotes: 0

Related Questions