Swift Programming – An Introduction

Programming in Swift Language

Swift 2.0

  • Swift is a powerful programming language for iOS, OSX and Watch OS with a consise yet expressive syntax.
  • One great thing about Swift is that it can co-exist with Objective C so untill and unless you are developing a brand new application, you can choose to continue having Objective
  • Code in your application and any new screens or functionalities can be developed using Swift.
  •  If you are developing a brand new OSX, iOS or Watch OS App, consider using Swift as the programming language
  • One beautiful thing about Swift 2.0 is you can include markdown syntax to add rich text and embedded images that display in Xcode’s Quick help.

What is Swift?

  • New programming language for Mac OSX App and iOS Apps
  • Swift is nicely integrated with Cocoa and Cocoa Touch
  • Swift uses ARC for memory management
  • Swifts has the power of Objective-C’s dynamic object model
  • Swift extensively uses constants to make code safer and cleaner.
  • Swift has datatypes which were not present in Objective C (e.g tuples that allows to create and pass around grouping of values)
  • One strikingly different thing about swift is, it does not use semicolon (;) after each statement. Semicolons are however required if you are writing multiple separate statements in a single line
  • Whenever a cocoa application or iOS application is created using Swift Language, the .h and .m is kind of combined together in one file with a “.swift” extension
  • In the below sample we have created a couple of functions to test variables and constants, type safety and type inference

In this article we will create a sample project for learning the nuances of Swift

Swift – Printing and Logging

func testPrintAndLogging()
        //Print & logging can be done using println or using NSLog
        //Note in the NSLog we are not using @"%@" rather "%@"
        println("Hello World")
        NSLog("%@", "Hello World!!!!")
        NSLog("aFloatValue %f", 8.12345)
        NSLog("anIntegerValue %d", 8)
        //Hello World
        //2014-06-02 18:49:02.085 IntroductionToSwift[2656:303] Hello World!!!!
        //2014-06-02 18:49:02.086 IntroductionToSwift[2656:303] aFloatValue 8.123450
        //2014-06-02 18:49:02.086 IntroductionToSwift[2656:303] anIntegerValue 8

        //The below line will give a compiler error as Swift does not allow c function.
        //printf("Hello World")

Swift – Printing a String

        let firstName = "John"

Swift – Print using string interpolation

        let age = 10
        println("\(firstName)'s age is \(age)")
        //John's age is 10

Swift – Printing an Array

        //Printing an array
        let nameArray = ["john","jane","mary","bill"]
        //[john, jane, mary, bill]
        Printing an element of an array
        String interpolation with an array element
        println("The 3rd element of nameArray is \(nameArray[3])")
        //The 3rd element of nameArray is bill

Swift – Printing float and Formatter float

        let salary = 1000.327
        println(salary)                 //1000.327
        println(String(format: "Salary = %.5f", salary)) //Salary = 1000.32700
        NSLog("Salary = %f", salary)    //Salary = 1000.327000
        NSLog("Salary = %2.2f", salary) //Salary = 1000.33

Swift – printing an int as string

        let experience = 10.5
        println(experience)     //10.5

Swift – Printing an array while maintaining the double quotes. Using debugPrintln

        let countryArray = ["USA","BRAZIL","MEXICO","CANADA"]
        //["USA", "BRAZIL", "MEXICO", "CANADA"]

Swift – print vs println 

        //print vs println in Swift
        //In the below case it will continue printing in the same line

Swift – printing the objects of a String Array

        var strArray = ["A","B","C","D","E"]
        for str in strArray{
        print(strArray) //[A, B, C, D, E]
        debugPrintln(strArray) //["A", "B", "C", "D", "E"]

Swift – Printing a Dictionary

        var employeeDictionary: Dictionary <String,String> = ["firstName":"John","lastName":"Doe"]
        //Prints [firstName: John, lastName: Doe]
        //Printing an Element of a Dictionary
        let fName = employeeDictionary["firstName"]
        println("First Name is \(fName)")
        //First Name is Optional("John")
        println("First Name is \(fName!)")
        //First Name is John

Swift – Printing File Paths

        //Printing the document file path
        println(NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString)
        //  /Users/debasisdas/Documents
        println(NSSearchPathForDirectoriesInDomains(.ApplicationDirectory, .UserDomainMask, true)[0] as NSString)
        //  /Users/debasisdas/Applications

Swift – Printing using ASCII

        //Printing Hebrew
        var content:String="\u{05D0} - aleph is a silent consonant"
        var content1:String="\u{200E}\u{05D0} - aleph is a silent consonant"

Swift – Printing Date

        //Printing Date, Printing Date Description With Locale
        let myDateDescription = NSDate().description // "2015-01-13 18:57:15 +0000"
        // you can also use it with current locale
        let myDateDescriptionWithLocale = NSDate().descriptionWithLocale(NSLocale.currentLocale())! 
        println(myDateDescription) //2015-03-22 00:44:48 +0000
        println(myDateDescriptionWithLocale) //Saturday, March 21, 2015 at 5:44:48 PM Pacific Daylight Time

Swift – Printing Elements of a Tuple

        //Printing Tuple
        //Unnamed Tuple
        let salesAndProfitTuple = (104.00, 15.19)
        println(salesAndProfitTuple.0) //104.0
        println(salesAndProfitTuple.1) //15.19
        //Named Tuple
        let salesAndProfitTupleNamed = (sales:400.00, profit:25.19)
        println("sales = \(salesAndProfitTupleNamed.sales)") //sales = 400.0
        println("Profit = \(salesAndProfitTupleNamed.profit)") //Profit = 25.19

Swift – Calling a function from a println Statement

        println("Greeting message is => " + greet("Good Morning !!! ", addressTo: "Mr Anderson"))
        //Greeting message is => Good Morning !!!  Mr Anderson

    func greet(message: String, addressTo: String) -> String {
        return "\(message) \(addressTo)"

Swift – Printing Variable and Object Types through Introspection

        var myvar0 = NSString() // Objective-C class
        var myvar1 = 42
        var myvar2 = "Hans"
        let myvar3 = NSDate();
        println( "TypeName0 = \(_stdlib_getTypeName(myvar0))")
        println( "TypeName1 = \(_stdlib_getTypeName(myvar1))")
        println( "TypeName2 = \(_stdlib_getTypeName(myvar2))")
        println( "TypeName3 = \(_stdlib_getTypeName(myvar3))")
            TypeName0 = NSString
            TypeName1 = _TtSi
            TypeName2 = _TtSS
            TypeName3 = NSDate

        //Print Swift Introspection
        var classname = reflect(myvar3).summary
        println(className)          //SwiftPrintTesting.AppDelegate
        println(myvar3.className)   //__NSDate

Swift – Variables and Constants (var & let)

   func testVariablesAndConstants(){
        //Variables and Constants
        var age = 42
        println(age) //Will print 42
        age = 90
        println(age) //Will Print 90
        let newAge = 92 //Declaring a constant using let
        println(newAge) //Will print 92.
        //the newAge constant cannot be reassigned to a new value. Trying to do so will give a compile time error
        //Type Annotation, Provide a type annotation when we are declaring a constant or variable to state the type of variable or constant being created.
        let aFloatValue:Float = 70.0
        println(aFloatValue); //Will print 70.0
        println("Hello "+String(aFloatValue)) //Will print Hello 70.0
        let apples = 3
        let oranges = 5
        let appleSummary = "I have \(apples) apples."
        let fruitSummary = "I have \(apples + oranges) pieces of fruit."
        println(appleSummary) //I have 3 apples.
        println(fruitSummary) //I have 8 pieces of fruit.
        //Integer Constant
        let anIntegerMaxValue:Int64 = Int64.max
        println(anIntegerMaxValue) //9223372036854775807
        let anIntegerMinValue:Int64 = Int64.min
        println(anIntegerMinValue) //-9223372036854775808
        let anUnsignedIntegerValue:UInt64 = UInt64.max
        println(anUnsignedIntegerValue) //18446744073709551615
        //Boolean Constants
        let isEvenNumber = true
        let isNewEvenNumber = TRUE
        println(isEvenNumber) //will print true
        println(isNewEvenNumber) //Will print 1
        //let isEvenNumber = YES //Objective C boolean is not allowed
/*        if (isNewEvenNumber) //This will give a compile error as CInt does not conform to logicValue protocol
        if (isEvenNumber)
            println("yes this is a even number") //will print - yes this is a even number

Swift – Type Safety and Type Inference

func testTypeSafeAndTypeInference(){
        var afloatValue:Float = 654.432 //Here it is explicitly stated that the aFloatValue is of type Float
        println(afloatValue) //654.432006835938

        var aValue = 42
        println(aValue) //42
        //In the above line of code it is not explicitly stated that aValue is an integer but Swift uses type inference to workout the appropriate type
        let aDoubleValue = 42 + 0.43212
        println(aDoubleValue) //aDoubleValue is inferred to be of type double
       //Will print 42.432120

Swift – Array of Dictionaries

       var dataArray:NSDictionary[] = [["FirstName": "Debasis", "LastName": "Das"],
          ["FirstName": "Nishant", "LastName": "Singh"],
          ["FirstName": "John", "LastName": "Doe"],
          ["FirstName": "Jane", "LastName": "Doe"],
          ["FirstName": "Mary", "LastName": "Jane"]];

(Vanila – Sample Cocoa Application using Swift)

Swift – Loading a PDF in a PDF Viewer

import Cocoa
import Quartz

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var pdfViewer: PDFView!

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        let fileURL:NSURL = NSBundle.mainBundle().URLForResource("SampleFile", withExtension: "pdf")!
        var pdfDocument:PDFDocument = PDFDocument.self.init(URL: fileURL)
Posted in Cocoa, Cocoa Touch, iOS, Swift Tagged with: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts

Hit Counter provided by technology news