What is the difference between these two statements?

Asked

Viewed 69 times

1

Let’s say I created a struct point that gives a certain point in a "map".

struct Ponto {
    let x: Int
    let y: Int

    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }

What would be the difference between creating a type variable Ponto and create a variable that contains Ponto as a value?

var ponto1: Ponto

//e

var ponto2 = Ponto(x: 1, y: -1)
  • No need to implement init basic using Structures. struct Ponto {
 let x, y: Int }

2 answers

1

The first is declaration of type var ponto1: Ponto, I mean, you’re just saying that the variable ponto1 is the type Ponto and there is no one instance, but the other var ponto2 = Ponto(x: 1, y: -1) is the instance of Ponto in the variable ponto2, has to be careful because the ponto1 is not a body and consequently has no access to its members.

struct Ponto {
  let x: Int
  let y: Int

  init(x: Int, y: Int) {
    self.x = x
    self.y = y
  }
}

var ponto1: Ponto = Ponto(x: 6,y: 3); // tipo e depois instância
var ponto2 = Ponto(x: 100, y: 200); // instância

print(ponto1.x);

Online Example


What I could also realize that it follows a nomenclature where to have a standard initial member with a builder overload has to do so:

struct Ponto {
  let x: Int;
  let y: Int;
  init() {
    self.x = 0;
    self.y = 0;
  }
  init(x: Int, y: Int) {
    self.x = x
    self.y = y
  }
}

and in the event that your instance works so:

var ponto0 = Ponto(); // valor padrão
var ponto1 = Ponto(x: 6,y: 3); // valor pelo construtor

Exit:

print(ponto0.x); // 0
print(ponto1.x); // 6

Online Example

If you only want members with default values you don’t need to create the constructor and directly pass the values in the members and swap let (defining a constant) for var (defining a variable) in the statement:

struct Ponto {
  var x: Int = 0;
  var y: Int = 0;
}

var ponto1: Ponto = Ponto();
var ponto2 = Ponto();

print(ponto1.x); // 0
print(ponto2.x); // 0

Really there are several concepts you need to understand and I recommend a read in the documentation.


References

1


The two are creating a variable of the type Ponto, the first does not create an instance of the object of type Ponto and if you try to access then it will give a build error, initializing after the declaration will work normally:

struct Ponto {
    let x: Int
    let y: Int
    init(x: Int, y: Int) {
      self.x = x
      self.y = y
    }
}
var ponto1: Ponto;
ponto1 = Ponto(x: 1, y: -1);
print(ponto1.x, ponto1.y);

I put in the Github for future reference.

The second creates and initializes the object with values passed in the constructor (the init()) that does what he has to do to initialize. In case he passed named arguments that is the Swift culture to make it more readable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.