8

I am trying to limit a classes scope to within a function. This seems to work:

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

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

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

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

... I get the following build errors:

  • Global is external, but doesn't have external or weak linkage!
  • invalid linkage type for function declaration
  • LLVM ERROR: Broken module found, compilation aborted!

Note: If I move the class out of the function's scope, the code compiles:

class MyClass {
    @lazy var s = ""
}

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

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
Senseful
  • 86,719
  • 67
  • 308
  • 465
  • 1
    Did you report this? https://bugreport.apple.com/ – aleclarson Jun 29 '14 at 00:32
  • I've also had some issues with lazy vars causing compiler crashes; in my case it was related to protocol conformance. Need to file that radar. :| – cmyr Dec 15 '14 at 21:39

2 Answers2

0

The following code works for me:

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

foo() // prints "qux"

Looks like there was a bug in the early Swift laguage version, which has been reolved.

akashivskyy
  • 44,342
  • 16
  • 106
  • 116
0

I can confirm akashivskyy's observation. I've tried it as well and the this code works for me as well:

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

foo() // "string" is printed

It's not the first time for me that I've actually encountered some issues in earlier Swift versions. I mean it's still a pretty young language and thus it needs always some improvements and bug fixes.

Are you using the newest version of Swift and Xcode?

fr33g
  • 2,249
  • 1
  • 12
  • 12