2
    struct Person
    {
        var personName:String?
        init(name:String) {
              personName=name
        }

    lazy var greetLazy:String =
    {
            return "Hello \(self.personName!)"
    }()

    func greetFunc()->String
    {
        return "Hello \(self.personName!)"
    }
}

var person:Person=Person(name:"")
print(person.greetLazy)
print(person.greetFunc())

I created 2 things viz a lazy property and a function to do the same thing. Now its said that the value of greetLazy will only be calculated when its first accessed,so when I access it using person.greetLazy it prints to the consoleand thats what lazy is supposed to mean.

My Question here is in case of function also the value will be returned only if i access the function. It wont precalculate it. So what would be the difference between the two in that case?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Piyush Vaish
  • 107
  • 8

2 Answers2

8

A full name of lazy properties in Swift is lazy stored property, which means that the value of the property is stored as soon as it is computed the first time it is needed. No additional computations is performed when you reference the same property again.

The result of a function, on the other hand, is computed each time that you call the function.

Here is your modified code that demonstrates this point:

struct Person {
    var personName:String?
    init(name:String) {
        personName=name
    }

    lazy var greetLazy:String = {
        print("Computing property...")
        return "Hello \(self.personName!)"
    }()

    func greetFunc()->String
    {
        print("Computing function...")
        return "Hello \(self.personName!)"
    }
}

var person:Person=Person(name:"")
print(person.greetLazy)
print(person.greetFunc())
print(person.greetLazy)
print(person.greetFunc())

Above prints "Computing property..." only once, while "Computing func..." is printed twice.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0
struct Person
{
    var personName:String?
    init(name:String) {
          personName=name
    }

lazy var greetLazy:String =
{
        return "Hello \(self.personName!)"
}()

func greetFunc()->String
{
    return "Hello \(self.personName!)"
}
}

var person:Person=Person(name:"alpha")
print(person.greetLazy)
print(person.greetFunc())

prints

Hello alpha
Hello alpha

lets continue and change the name

person.personName = "beta"
print(person.greetLazy)
print(person.greetFunc())

It prints

Hello alpha
Hello beta

The difference is self explanatory, isn't it?

See another example

user3441734
  • 16,722
  • 2
  • 40
  • 59