Disclaimer: I'm attempting the following exercise because I think it will be instructive. I'm interested in how it might be done. So please don't be too hasty to jump in with "This is the wrong way to do it, you should never do it like this!"
Working from the commandline with my favourite text editor, I would like to construct a minimal Swift program that displays a window.
It's a GUI/Cococa hello world, if you like.
In the same spirit, I want to avoid NIB.
So, No XCode, No NIB.
I would like to:
- compile it with the swift compiler
- create a #! swift script which runs using the Swift interpreter
If I can do both of those things I will feel my feet on the ground and be much more at ease upgrading to Xcode.
I tried the following:
window.swift
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
let newWindow = NSWindow(contentRect : NSScreen.mainScreen()!.frame
, styleMask : NSBorderlessWindowMask
, backing : NSBackingStoreType.Buffered
, defer : false)
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
newWindow.opaque = false
newWindow.movableByWindowBackground = true
newWindow.backgroundColor = NSColor.whiteColor()
newWindow.makeKeyAndOrderFront(nil)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
However, attempting to run this from the command line fails:
[email protected] ~ /Users/pi/dev/macdev:
⤐ swift window.swift
window.swift:3:1: error: 'NSApplicationMain' attribute cannot be used in a
module that contains top-level code
@NSApplicationMain
^
window.swift:1:1: note: top-level code defined in this source file
import Cocoa
^
✘
What's the correct way to eliminate the error?
Make a file TestView.swift (like this):
Make a file TestApplicationController.swift (like this):
Make a file main.swift (like this):
The last file must not be renamed, main.swift is apparently a special name for swift (otherwise the example will not compile).
Now, enter this (to compile the example):
Run the code by entering:
It shows a main window (centered) with a nice green collor and a yellow rectangle within it). You can kill the app by entering Control-C.
Note that this is a swift compilation not an interpreter running, so you have a native app.
Note that -sdk and the path to MacOSX10.11.sdk is essential (otherwise the code will not compile).
Note also that this compilation depends on the latest Xcode distribution, so update MacOSX10.11.sdk to MacOSX10.10.sdk or whatever is in the SDKs directory.
It took a while to find this out ...