Xcode6.3.2 Swift bug with static constants

164 Views Asked by At

I am trying to figure out why I am having constant compile problems with this type of construct in Xcode 6.3.2.

class Foo {
  static let CONSTANT_NAME = "CONSTANT_STRING"
  ...
  func bar () -> String {
    var s = String(format:"%s,%d\n", CONSTANT_NAME, 7)
    return s
  }
  ...
}

As I understand the language, this should be perfectly legal code however Xcode is constantly (hah-pun) having issues with it raising the error

"there is no member CONSTANT_NAME in class Foo"

If I get lucky and force it to clean, and then rebuild it will some times sort itself out and work. Other times, even doing that, then trying an open/close project will still not resolve the issue.

So, I guess my implicit follow up question (if the answer to the above is - it is legal code) is: is the Xcode Swift compiler that buggy that even basic things like this are likely to cause problems? If so, swift seems to be in a pretty bad state.

3

There are 3 best solutions below

2
On

static is class property, that means you have to call it like this ClassName.property

class Foo {
    static let CONSTANT_NAME = "CONSTANT_STRING"
    func bar () -> String {
        var s = String(format:"%s,%d\n", Foo.CONSTANT_NAME, 7)
        return s
    }
}

That is not a bug. That is what it should be. A class property "belongs" to the class.

If you want your code work without using ClassName, do not use static

class Foo {
    let CONSTANT_NAME = "CONSTANT_STRING"
    func bar () -> String {
        var s = String(format:"%s,%d\n",CONSTANT_NAME, 7)
        return s
    }
}

More details in the Apple Documentation

2
On

The static let syntax is legal and valid. The issue is that you must fully qualify that variable when you access it:

var s = String(format:"%s,%d\n", Foo.CONSTANT_NAME, 7)

The compiler error is a bit obtuse, but it is telling the truth... CONSTANT_NAME is not a member, but a type property of class Foo: Swift Type Properties

1
On

I hear you about saving key strokes. I've personally been trying to make my Swift code as idiomatic as possible by milking every short cuts but when you find code like this, you should be glad that the compiler asks you to keep on the safe side:

class Foo {
    static let CONSTANT = "hello"

    func bar() -> String {
        let CONSTANT = "bye"
        return CONSTANT // I know which one! Thanks Swift!
    }
}
println(Foo.CONSTANT)
println(Foo().bar())