2

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

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

whats the difference between your two examples?
@BlazeyJohn Refer this for difference between ? and ! stackoverflow.com/questions/25895098/…
1

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

1 Comment

Since Swift 1.2 this expression is valid: developer.apple.com/swift/blog/?id=22
0

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
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.