Can't access Singleton instance from Swift struct

Using Xcode 6.3, I created a very simple, contrived command line tool in Swift. It contains three modules.

The main module:

import Foundation

let displayer = ValueDisplayer()

displayer.displayValue()

      

ValueDisplayer module:

import Foundation

class ValueDisplayer {
    func displayValue() {
        println("The value is \(ValueProvider.instance.value)")
    }
}

      

and the ValueProvider module:

import Foundation

public class ValueProvider {
    class var instance: ValueProvider {
        struct Static {
            static let instance = ValueProvider()
        }

        return Static.instance
    }

    var value: Int {
        return Int(arc4random())
    }
}

      

All of this is compiled and completed successfully. However, I decided to convert the ValueProvider to a struct. I created a Cocoa Framework target and moved the ValueProvider module into it, not on the command line. I changed the ValueDisplayer module as follows:

import Foundation
import ValueProvider

class ValueDisplayer {
    func displayValue() {
        println("The value is \(ValueProvider.instance.value)")
    }
}

      

and configured the command line tool to bind to the framework. Now I am getting the following compilation error in the ValueDisplayer unit associated with the println statement:

Module 'ValueProvider' has no name named 'instance'

I'm confused why the code doesn't work anymore. I am wondering if the ValueProvider class will no longer qualify correctly, just not clear how this should be done.

What is required for the command line tool to compile by linking to the framework?

+3


source to share


2 answers


public

is a "refusal". It does not magically apply to members of a public unit; you must explicitly apply it to a member of a public object if you want that member to be public as well. You have made the class ValueProvider

public, but you have not made its var class instance

public, so it is not visible from another module.

So, you need to rewrite like this:



public class ValueProvider {
    public class var instance: ValueProvider {
        // ...
    }
    public var value: Int {
        // ...
    }
}

      

[And by the way, the file is not a module. A structure is a module. This is why you need to change your code when you move it, just being in a separate file, while in a different structure.]

+4


source


I had a build and run program. I needed to go to Build Phases for the framework and remove the generated header file from the Headers section . I don't know why this makes it work. I understand that the header is required to interact with Objective-C. If a program needed to interact with Objective-C as well as Swift, I wondered how someone could get things to work correctly.



+1


source







All Articles