Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a struct or class in Swift?

Tags:

swift

I have a struct called Person in this code in the down, I am creating an instance of it, like this one:

let peson: Person = Person(name: "Dan", age: 21)

But I noticed that we can make it with this code as well:

let peson: Person = { Person(name: "Dan", age: 21) }()

So what is the difference? When I should use first way and when I should use second way?

struct Person {

    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    
}
like image 538
ios coder Avatar asked Oct 31 '25 01:10

ios coder


1 Answers

The anonymous closure is an unnamed function. It's useful whenever you want to initialize something with the result of calling a function, but you don't want to write a function like:

  func makeDan() -> Person {
     ...
  }

  let person = makeDan()

That would mean you have to come up with a name for the function and find some place to put it, which means it's also visible and can be called by other pieces of code that don't need anything to do with makeDan. It's often useful to have functions that have no names.

Needing a function to initialise something is useful when you have something complex that needs some kind of computation, so multiple lines of stuff. It's also useful when the initialization is only wanted to be done if/when required:

lazy var dan: Person = { ... }()

Perhaps because the computation is expensive in some kind of resource use, like cpu or memory. Or possibly because the computation involves some kind of side effect, like opening a database or something, that's only wanted if/when the property is used.

like image 134
Shadowrun Avatar answered Nov 01 '25 19:11

Shadowrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!