Swift: Hello World

Nearly everything you do in a normal Objective-C Cocoa-Touch project is mirrored in the Swift version. Yes, there’s an awful lot of dot notation (a victory for those of us who are propertyholics, I suppose) and a heavy emphasis on parentheses. The flow and structure of your usual patterns remain, enabling you to minimize transition times between the languages.

/*
Erica Sadun, https://ericasadun.com
*/

import UIKit

class ViewController: UIViewController
{
    override func loadView()
    {
       // Build a view
        self.view = UIView()

        // Set the background color and title
        self.view.backgroundColor = UIColor.greenColor()
        self.title = "Hello World"
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
    // The window is a local instance variable
    var window: UIWindow?

    func application(application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
    {
        // Build the window
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        self.window!.backgroundColor = UIColor.whiteColor()

        // Create a nav/vc pair using the custom ViewController class
        // Thanks, Eoin Norris for the tweakage
        let nav = UINavigationController()
        let vc = ViewController(nibName: nil, bundle: nil)

        // Push the vc onto the nav
        nav.pushViewController(vc, animated: false)

        // Set the window’s root view controller
        self.window!.rootViewController = nav

        // Present the window
        self.window!.makeKeyAndVisible()
        return true
    }
}

One Comment

  • To get an iOS playground: New>File>iOS>Source>Playground