6

It is my understanding that as of Xcode 6.3 / Swift 1.2, I can use static variables and methods inside of a class. However, the compiler doesn't like it when I try to initialize a static variable by calling a static function (I get the error 'Use of unresolved identifier getDefaultString' in the example below). Here is a snippet that demonstrates my problem:

import Foundation

public class Settings {
    private static var _bundle = NSBundle.mainBundle()
    static func getDefaultString(key: String) -> String {
        return _bundle.objectForInfoDictionaryKey(key) as! String
    }

    private static var _server = getDefaultString("DefaultServer")
    public class var server: String {
        get { return _server }
        set { _server = newValue }
    }
}

Can someone help me understand why I can't do this?

2
  • Does it work if you use private static var _server = Settings.getDefaultString("DefaultServer")? Commented Jun 15, 2015 at 20:40
  • 1
    As a matter of fact, it does. But I don't understand why? Commented Jun 15, 2015 at 20:43

2 Answers 2

14

This should work:

private static var _server = Settings.getDefaultString("DefaultServer")

I do not know exactly why, it seems that there is some sort of an assumption in the play that a method without type qualified in front of it is an instance method. But that does not fully work as well. E.g. this produces interesting result in playground:

    class Foo {

        static func initFoo() -> String {
            return "static"
        }

        func initFoo() -> String {
            return "instance"
        }

        static var foo: String = initFoo()

    }

    Foo.foo

... no need to qualify type in front of initFoo(), but still the static one is picked up. A minor bug probably.

Sign up to request clarification or add additional context in comments.

Comments

1

You are forcing an unwrap of a possible (and actual) nil object.

return _bundle.objectForInfoDictionaryKey(key) as! String

NSBundle's objectForInfoDictionaryKey can return nil – its declaration:

func objectForInfoDictionaryKey(key: String) -> AnyObject?

my edit, as a playground:

import Foundation

class Settings {
    private static var _bundle = NSBundle.mainBundle()
    static func getDefaultString(key: String) -> String? {
        return _bundle.objectForInfoDictionaryKey(key) as? String
    }

    private static var _server = Settings.getDefaultString("DefaultServer")

    class var server: String? {
        get { return _server }
        set { _server = newValue }
    }
}

Settings.server

You can, of course, fallback from a nil in some other fashion if you prefer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.