Why can't I initialize a static variable by calling a static function in Swift?

I understand that with Xcode 6.3 / Swift 1.2 I can use static variables and methods inside the class. However, the compiler does not like this when I try to initialize a static variable by calling a static function (I get the error message "Using an 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?

+5
source share
2 answers

This should work:

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

I don’t know exactly why, it seems that there is some assumption in the game that a method that does not have a type corresponding to it is an instance method. But this does not fully work. For instance. this creates an interesting result on the playground:

  class Foo { static func initFoo() -> String { return "static" } func initFoo() -> String { return "instance" } static var foo: String = initFoo() } Foo.foo 

... there is no need to assign a type before initFoo (), but still a static one is selected. Probably a minor mistake.

+11
source

You force to deploy a possible (and actual) nil object.

 return _bundle.objectForInfoDictionaryKey(key) as! String 

NSBundle objectForInfoDictionaryKey can return nil - its expression:

 func objectForInfoDictionaryKey(key: String) -> AnyObject? 

my editing 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, back out from nil some other way if you want.

0
source

All Articles