Swift – Apple’s New Programming Language

Apple is awesome 🙂 , they always look towards something new ! Objective C is pretty old , yeah its 20+ years old now, so Apple thought its time to change now, and we have Swift with us now.

All About Swift you should know

Swift is a multi-paradigm programming language developed by Apple for use with iOS and OS X. Designed to replace Objective C, work began on Swift in 2010 and the first mobile app was debuted in June 2014 at the Worldwide Developers Conference. Despite its goal of replacing Objective C, Swift is capable of working flawlessly alongside the more dated Objective C language while using the Cocoa and Cocoa Touch frameworks. Swift adopts safe programming patterns and adds modern features to make programming easier, modern, powerful, expressive, and flexible.

Apple laid the foundation for Swift by advancing its existing compiler, debugger, and framework infrastructure. Memory management was simplified with Automatic Reference Counting (ARC). The framework stack, built on the solid base of Foundation and Cocoa, has been modernized and standardized throughout. Objective-C itself has evolved to support blocks, collection literals, and modules, enabling framework adoption of modern language technologies without disruption. With this groundwork, they introduce a new language Swift for the future of Apple software development.

It is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language. It supports playgrounds, an innovative feature that allows programmers to experiment with Swift code and see the results immediately, without the overhead of building and running an app.

What are the requirements?

  • Developer access to Xcode 6 beta
  • A Mac computer that can run Xcode 6
  • Work with Xcode’s new .playground file

How is Swift Efficient?

Fast : Swift was built to be fast. Compiles and optimizes with the advanced code analysis in LLVM compiler included in Xcode 6 beta, and uses the Objective-C runtime, allowing Objective-C, Objective-C++ and Swift code to run within a single program.

This creates high-performance apps by transforming Swift code is into optimized native code, in turn to get the most out of modern Mac, iPhone, and iPad hardware.

Complete platform : It provides object-oriented features such as classes, protocols, and generics, giving Cocoa and Cocoa Touch developers the performance and power they demand from the frameworks with swift.

Safe by design : Eliminate huge categories of bugs, crashes, and security holes. Swift pairs increased type safety with type inference, restricts direct access to pointers, and automatically manages memory using ARC, making it easy for you to use Swift and create secure, stable software. Other language safety related features include mandatory variables initialization, automatic bounds checking to prevent overflows, conditionals break by default, and elimination of pointers to direct memory by default.

Modern : Write, debug, and maintain less code, with an easy to write and read syntax, and no headers to maintain. Swift includes optionals, generics, closures, tuples, and other modern language features. Inspired by and improving upon Objective-C, Swift code feels natural to read and write.

Interactive: Use Swift interactively to experiment with your ideas and see instant results.

Unified : A complete replacement for both the C and Objective-C languages. Swift provides full object-oriented features, and includes low-level language primitives such as types, flow control, and operators

How Swift works?

  • You don’t need to import a separate library for functionality like input/output or string handling.
  • Code written at global scope is used as the entry point for the program, so you don’t need a main function.
  • You also don’t need to write semicolons at the end of every statement.
  • Swift provides its own versions of all fundamental C and Objective-C types, including Int for integers; Double and  Float for floating-point values; Bool for Boolean values; and String for textual data. Swift also provides powerful versions of the two primary collection types, Array and Dictionary.
  • Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values cannot be changed. These are known as constants, and are much more powerful than constants in C. Constants are used throughout Swift to make code safer and clearer in intent when you work with values that do not need to change.
  • Use let to make a constant and var to make a variable.
  • The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.

let constantValue = 88

  • A constant or variable must have the same type as the value you want to assign to it.
  • However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type.
  •  In the example below, the compiler infers that myVariable is an integer because its initial value is a integer.

var myVariable = 44

myVariable = 63

  • If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.

let integerConstant = 65

let doubleConstant = 65.0

let explicitDoubleConstant: Double = 70

  • Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.

let widthString = "The width is "

let widthValue = 94

let widthLabel = widthString + String(widthValue)

let apples = 3

let oranges = 5

let appleSummary = "I have \(apples) apples."

let fruitSummary = "I have \(apples + oranges) pieces of fruit."

  • Collection Types

Swift provides two collection types, known as arrays and dictionaries, for storing collections of values. Arrays store ordered lists of values of the same type. Dictionaries store unordered collections of values of the same type, which can be referenced and looked up through a unique identifier (also known as a key).

  • Arrays :

Create arrays and dictionaries using brackets ([]), and access their elements by writing the index or key in brackets.

The example below creates an array called shoppingList to store String values. The shoppingList variable is declared as “an array of String values”, written as String[].

var shoppingList: String[] = ["Eggs", "Milk"]

// shoppingList has been initialized with two initial items

To find out the number of items in an array, check its read-only count property,

println("The shopping list contains \(shoppingList.count) items.")

// prints “The shopping list contains 2 items.”

Use the Boolean isEmpty property as a shortcut for checking whether the count property is equal to 0:

if shoppingList.isEmpty {

     println(“The shopping list is empty.”)

} else {

     println(“The shopping list is not empty.”)

}

// prints “The shopping list is not empty.”

You can add a new item to the end of an array by calling the array’s append method:

shoppingList.append("Flour")

// shoppingList now contains 3 items, and someone is making pancakes

Alternatively, add a new item to the end of an array with the addition assignment operator (+=):

shoppingList += "Baking Powder"

// shoppingList now contains 4 items

You can also append an array of compatible items with the addition assignment operator (+=):

shoppingList += ["Chocolate Spread", "Cheese", "Butter"]

// shoppingList now contains 7 items

Retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array:

var firstItem = shoppingList[0]

// firstItem is equal to “Eggs”

Note that the first item in the array has an index of 0, not 1. Arrays in Swift are always zero-indexed.

You can use subscript syntax to change an existing value at a given index:

shoppingList[0] = "Six eggs"

// the first item in the list is now equal to “Six eggs” rather than “Eggs”

You can also use subscript syntax to change a range of values at once, even if the replacement set of values has a different length than the range you are replacing. The following example replaces “Chocolate Spread”, “Cheese”, and “Butter” with “Bananas” and “Apples”:

shoppingList[4...6] = ["Bananas", "Apples"]

// shoppingList now contains 6 items

To insert an item into the array at a specified index, call the array’s insert(atIndex:) method:

shoppingList.insert("Maple Syrup", atIndex: 0)

// shoppingList now contains 7 items

// “Maple Syrup” is now the first item in the list

Remove an item from the array with the removeAtIndex method. This method removes the item at the specified index and returns the removed item (although you can ignore the returned value if you do not need it):

let mapleSyrup = shoppingList.removeAtIndex(0)

// the item that was at index 0 has just been removed

// shoppingList now contains 6 items, and no Maple Syrup

// the mapleSyrup constant is now equal to the removed “Maple Syrup” string

Iterating Over an Array

You can iterate over the entire set of values in an array with the for-in loop:

for iteminshoppingList {

      println(item)

}

If you need the integer index of each item as well as its value, use the global enumerate function to iterate over the array instead. The enumerate function returns a tuple for each item in the array composed of the index and the value for that item. You can decompose the tuple into temporary constants or variables as part of the iteration:

for (index, value) inenumerate(shoppingList) {

       println(“Item \(index + 1): \(value)”)

}// Item 1: Six eggs

  • Dictionary :

A dictionary is a container that stores multiple values of the same type. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier

Swift’s dictionary type is written as Dictionary<KeyType, ValueType>,where KeyType is the type of value that can be used as a dictionary key, and ValueType is the type of value that the dictionary stores for those keys.

The only restriction is that KeyType must be hashable—that is, it must provide a way to make itself uniquely representable. All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default, and all of these types can be used as the keys of a dictionary.

In a dictionary literal, the key and value in each key-value pair are separated by a colon. The key-value pairs are written as a list, separated by commas, surrounded by a pair of square brackets:

[key 1: value 1, key 2: value 2, key 3: value 3]

var airports: Dictionary<String, String> = [“TYO”: “Tokyo”, “DUB”: “Dublin”]

The airports dictionary is declared as having a type of Dictionary<String, String>, which means “aDictionary whose keys are of type String, and whose values are also of type String”.

You access and modify a dictionary through its methods and properties, or by using subscript syntax. As with an array, you can find out the number of items in a Dictionary by checking its read-only count property:

println("The dictionary of airports contains \(airports.count) items.")

// prints “The dictionary of airports contains 2 items.”

You can add a new item to a dictionary with subscript syntax. Use a new key of the appropriate type as the subscript index, and assign a new value of the appropriate type:

airports["LHR"] = "London"

// the airports dictionary now contains 3 items

You can also use subscript syntax to change the value associated with a particular key:

airports["LHR"] = "London Heathrow"

// the value for “LHR” has been changed to “London Heathrow”

As an alternative to subscripting, use a dictionary’s updateValue(forKey:) method to set or update the value for a particular key. Like the subscript examples above, the updateValue(forKey:) method sets a value for a key if none exists, or updates the value if that key already exists. Unlike a subscript, however, the updateValue(forKey:) method returns the old value after performing an update. This enables you to check whether or not an update took place.

The updateValue(forKey:) method returns an optional value of the dictionary’s value type. For a dictionary that stores String values, for example, the method returns a value of type String?, or “optional String”. This optional value contains the old value for that key if one existed before the update, or nil if no value existed:

if letoldValue = airports.updateValue("Dublin International", forKey: "DUB") {

      println(“The old value for DUB was \(oldValue).”)

}

// prints “The old value for DUB was Dublin.”

You can use subscript syntax to remove a key-value pair from a dictionary by assigning a value of nil for that key:

airports["APL"] = "Apple International"

// “Apple International” is not the real airport for APL, so delete it

airports[“APL”] = nil

// APL has now been removed from the dictionary

Alternatively, remove a key-value pair from a dictionary with the removeValueForKey method. This method removes the key-value pair if it exists and returns the removed value, or returns nil if no value existed:

if letremovedValue = airports.removeValueForKey("DUB") {

    println(“The removed airport’s name is \(removedValue).”)

} else {

    println(“The airports dictionary does not contain a value for DUB.”)

}

// prints “The removed airport’s name is Dublin International.”

Iterating Over a Dictionary

You can iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:

for (airportCode, airportName) inairports {

    println(“\(airportCode): \(airportName)”)

}

// TYO: Tokyo

// LHR: London Heathrow

For more about the for-in loop, see For Loops.

You can also retrieve an iteratable collection of a dictionary’s keys or values by accessing its keys and values properties:

for airportCodeinairports.keys {

   println(“Airport code: \(airportCode)”)

}

// Airport code: TYO

// Airport code: LHR

for airportNameinairports.values {

     println(“Airport name: \(airportName)”)

}

// Airport name: Tokyo

// Airport name: London Heathrow

  • To create an empty array or dictionary, use the initializer syntax.

let emptyArray = String[]()

let emptyDictionary = Dictionary<String, Float>()

  • If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:]—for example, when you set a new value for a variable or pass an argument to a function.

shoppingList = [] // Went shopping and bought everything.

  • Swift introduces advanced types not found in Objective-C. These include tuples, which enable you to create and pass around groupings of values. Tuples can return multiple values from a function as a single compound value.
  • Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nilpointers in Objective-C and are at the heart of many of Swift’s most powerful features.
  • Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process

Leave a Reply

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


The reCAPTCHA verification period has expired. Please reload the page.