Accessing code from SharedCode.swift in UserModule from Main Playground

Creating a new Swift Playground in the Playgrounds App on iPad or macOS, I get an empty Playground, and a UserModule with a SharedCode.swift file in it. In SharedCode.swift there’s just a comment that says:

// Code inside modules can be shared between pages and other source files.

I added a simple function to it:

func hello() {
    print ("hello")
}

Then I tried calling hello() from the main playground. I get the error “Cannot find ‘hello’ in scope.”

I can see, from auto-completion, that UserModule is a known entity in the main playground’s scope. But I don’t know how to set things up so that I can access my hello function, and I can’t find anything helpful in the docs. Could someone point me in the right direction, please?

Answered by CuriousJorge in 728631022

Ah. It seems that as a function defined in a module, it won't be visible without being prefixed with public, like so:

public func hello() {
    print("hello")
}

I found this out by watching the Swift Playgrounds 3 video from WWDC 2019. Once I had that basic step, I knew what sort of thing to look up. From there I figured out that I'd get more relevant information in the "Access Control" chapter of "The Swift Programming Language" book that Apple publishes. It is really hard to know where to look for information, sometimes! I hope this helps someone else.

Accepted Answer

Ah. It seems that as a function defined in a module, it won't be visible without being prefixed with public, like so:

public func hello() {
    print("hello")
}

I found this out by watching the Swift Playgrounds 3 video from WWDC 2019. Once I had that basic step, I knew what sort of thing to look up. From there I figured out that I'd get more relevant information in the "Access Control" chapter of "The Swift Programming Language" book that Apple publishes. It is really hard to know where to look for information, sometimes! I hope this helps someone else.

Accessing code from SharedCode.swift in UserModule from Main Playground
 
 
Q