Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Without #import, does Swift have its own easy way to detect circular dependencies?

Tags:

swift

#import "whatever.h"

...wasn't perfect, but it was very handy for diagnosing circular dependencies, not to mention enforcing modularity.

You could be certain which classes knew about other classes--with the flick of a finger.

If you had to, you could comment out all the import statements, and add them back one at a time, in order to diagnose a dependency issue. It wasn't necessarily fast but it was dead simple.

And if a class didn't import anything other than the obligatory headers, Son, that's one modular class you had there!

If your project had ten classes that didn't import anything, then you knew that they were ten modular classes--you didn't have to package each class into its own Framework or anything like that. Easy.

But now, with Swift's policy of "everybody knows about everything all the time", it seems like it's just down to personal vigilance to sustain modularity. Personal vigilance is the worst kind!

Am I missing something? Is there a way to do these things easily in Swift?

like image 805
Le Mot Juiced Avatar asked Apr 03 '15 20:04

Le Mot Juiced


1 Answers

If you want to modularize your Swift code, you should be using modules!

Creating a new module is pretty simple.

Add a new target to your project by clicking the plus sign here:

enter image description here

Select "Framework & Library" for the appropriate platform (iOS/OS X):

enter image description here

Choose "Cocoa Framework" (or Cocoa Touch, platform dependent) and click Next:

enter image description here

Give your module a name and change the language to Swift (or leave it as Objective-C, it doesn't matter, you can use both).

enter image description here

Add a Swift file to your module:

enter image description here

Add some code to your Swift file. Note, the default access level for Swift is internal which means it can be accessed from anywhere within the module but not from outside the module. Any code which we want to use outside the module must be given the public access level.

public class ModularSwift {
    public init(){}
    public var foo: Int = 0
}

Be sure to build your module (Cmd+B):

enter image description here

Go back to your original target, import the module and start using its code:

import MyModularSwiftCode

let foo = ModularSwift()

Xcode is perfectly happy:

enter image description here

Now, comment out the import statement and notice the errors:

enter image description here

like image 137
nhgrif Avatar answered Oct 17 '22 17:10

nhgrif