Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access class in different file

I'm still a newbie to swift and I can't get a clear answer on a couple things.

So far I've just been using a single file in playgrounds. If I want to use more files, how can I access data (variables and functions) from classes created there in my main file that controls the view?

From what I understand having multiple files would just be for convenience so I don't have could to write it again.

(Also on the side) what does it mean when a function has private, public or just 'func'?

I'm using swift 3 playgrounds

Thanks

like image 612
David Williamson Avatar asked Oct 17 '22 15:10

David Williamson


1 Answers

Making things public will make them importable from other modules. Making it private will make it only accessible by methods within its containing scope (encapsulation). For code that lives at the top level, this scope is the entire .swift file it lives in. Without either access modifier (just bare “func”), your thing will default to internal, which means it is accessible from any other code within the same module, but not by code in a different module.

A special case is the fileprivate modifier which restricts access to the .swift file the code lives in. For code that does not live in a class or struct, this does the exact same thing as private. Some Swift designers discourage use of this modifier, and it may be removed in future versions of Swift.

There is a fifth access modifier in Swift, open, which does the exact same thing as public, except it also allows subclassing, and only applies to classes. This one is rarely used, but useful for certain library interfaces.

To import all the public symbols in a module, use

import Module

To import a single public symbol, use

import var Module.variable
import func Module.function
import struct Module.structure
import class Module.class
...
like image 160
taylor swift Avatar answered Oct 21 '22 03:10

taylor swift