Using @lazy properties in functions causes build errors

I am trying to limit the scope of classes inside a function. This seems to work:

func foo() { class MyClass { var s = "" } } 

I can create instances of MyClass inside the foo () function.

However, when I try to add the @lazy specifier to the property ...

 func foo() { class MyClass { @lazy var s = "" } } 

... I get the following build errors:

  • Global external, but has no external or weak connection!
  • Invalid link type for function declaration
  • LLVM ERROR: broken module detected, compilation canceled!

Note. If I move the class out of scope, the code compiles:

 class MyClass { @lazy var s = "" } 

Why does this fail, and how should this error be resolved? If it cannot be resolved, is there another way to use @lazy properties inside functions?

+6
source share
2 answers

The following code works for me:

 func foo() -> String { class bar { lazy var baz = "qux" } return bar().baz } foo() // prints "qux" 

It appears that an error occurred in the earlier version of swift laguage, which was resolved.

0
source

I can confirm the Akashiv observation. I tried too, and this code works for me too:

 func foo() { class MyClass { var variable = "string" } let instance = MyClass() println(instance.variable) } foo() // "string" is printed 

This is not the first time for me that I encountered some problems in earlier versions of Swift. I mean, this is still a fairly young language, and therefore it always needs some improvements and bug fixes.

Are you using the latest version of Swift and Xcode?

0
source

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


All Articles