No, in your particular case, the compiler does not currently optimize c and / or k for constant expressions that are evaluated only once (this can be seen by examining IR in an optimized assembly) - although this can all be changed with future versions of the language.
However, it is worth noting that currently this can be done for simpler expressions, for example:
func foo() -> Int { return 2 + 4 }
The compiler can evaluate the addition at compile time, so the function simply does return 6 (and then it can be inlined). But, of course, you should only worry about such optimizations in the first place, if you really identified this function as a performance bottleneck.
One of the nice tricks to get static constants in a function is to define an indifferent enum with static properties in the function area, in which you can define your constant expressions:
func test() -> String { enum Constants { static let c = Array("abc".characters) static let k = UInt32(c.count) } let r = Int(arc4random_uniform(Constants.k)) return String(Constants.c[r]) }
Now both initializer expressions for c and k will be evaluated only once, and this will be done when they are first used (for example, when the function will be called first).
And of course, as you show, you can use the instantly evacuated closure to have a multi-line initialization expression:
enum Constants { static let c: [Character] = {
source share