2

So while learning Swift, I came across two ways to initialize parameters in a struct,

struct Fruit {
  let name: String
}

let _ = Fruit(name: "Apple")

or,

struct Fruit {
  let name: String

  init(name: String) {
    self.name = name
  }
}

let _ = Fruit(name: "Apple")

What is the difference between two or maybe which one is correct?

1
  • 4
    Both forms are identical. In a struct (unlike a class) you get the memberwise initializer for free. The explicit declaration is redundant. Commented Nov 26, 2021 at 10:29

1 Answer 1

2

-> For structure, we don't need to write initializer explicitly (init) as it is already included by default if attributes are not optional.

-> For classes, we have to define initializer explicitly.

-> 1st option is correct when it comes to structures.

-> if you don't want to take parameters as compulsory while creating an object of structure you can make attributes options like this

struct Sample {
   var x: Int?
}

-> For more information regarding structures and classes you can follow this link :- https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html

Sign up to request clarification or add additional context in comments.

4 Comments

This is incorrect. For classes you have to explicitly state the initializer, for structs it is automatically synthesised , however you can have an initializer for structs and there is nothing wrong with that. In fact you will have to create an initializer for a struct if it is contained in a separate module due to the fact that the synthesised initializer is marked internal.
is it ok now..?
If the struct is in another module, the generated initializer is not always accessible.
struct a { var x:Int var y: b } struct b { var z:Int }. var ab = a(x: 1, y: b(z: 3))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.