Swift: implement protocol variable as lazy var?

It seems that it is not possible to implement the variable required by the protocol with a lazy variable. For instance:

protocol Foo {
  var foo: String { get }
}

struct Bar: Foo {
  lazy var foo: String = "Hello World"
}

The compiler complains that Type 'Bar' does not conform to protocol 'Foo'.

It is also not possible to add a keyword lazyto the protocol declaration, because after that you get an error 'lazy' isn't allowed on a protocol requirement.

So is that not possible at all?

+4
source share
1 answer

Citation Language Guide - Properties - Stairway Saved Properties [emphasis mine]:

A lazy stored property is a property whose initial value is not calculated before first use.

I.e., . foo foo get, nonmutating get, Bar lazy foo, mutating getter.

Bar foo ( ):

protocol Foo {
    var foo: String { get }
}

class Bar: Foo {
    lazy var foo: String = "Hello World"
}

, foo foo, mutating getter.

protocol Foo {
    var foo: String { mutating get }
}

struct Bar: Foo {
    lazy var foo: String = "Hello World"
}

mutating/nonmutating . Q & A:

+10

Source: https://habr.com/ru/post/1691619/


All Articles