I was trying to make PracticalSwift’s simple web browser work with Swift 2.0 and it turned out the changes were only minimal. In order to be able to run Cocoa programs written in Swift 2.0 you still need to install Xcode 7 but we will not use Xcode at all in this article. Check that you have Swift 2.0 installed, and find where it is located:
Now create a new Swift file in the terminal:
As a quick vi refresher, to insert text use the i key, and when you are done press the Esc key to exit the edit mode, and then type :wq to save and quit vi. Make sure the first line contains the shebang symbol (#!) followed by the path we found above. This line tells the Swift compiler to run the file without compiling it:
Next we import WebKit and set up the application. We could just import Cocoa because that is all we need to run a graphical Cocoa application, but we also need WebKit later, and it turns out WebKit already imports Cocoa so we can save one redundant import this way. Every Cocoa app needs exactly one instance of NSApplication instantiated. Then we set the activation policy of this app to regular which means this app will appear in the Dock:
Then we create a window for our web browser, set its size and style, center it, set a title for it, and finally show it:
Next we create and connect a window delegate that will terminate the application when the close window button is clicked:
Finally, we create an application delegate that we need in order to create the WebView object. Then we connect the application delegate, and set the app up so we can run it:
Exit the edit mode, save and quit vi. Finally, change the permissions for our file to make it executable, and then run it.
There is our beautiful web browser. Thanks, PracticalSwift, for the nice introduction to writing a minimal web browser.
Until next time!