Apple’s New Swift Programming Basics

Apple’s New Swift Programming Basics

Introduction

Along with the announcement of iOS 8 and Yosemite, Apple surprised all developers in the WWDC by launching a new programming language called Swift. Swift is advertised as a “fast, modern, safe, interactive” programming language. The language is easier to learn and comes with features to make programming more productive. The syntax of Swift would be more familiar to web developers. If you have some programming experience with JavaScript (or other scripting languages), it would be easier for you to pick up Swift rather than Objective-C.

Use Case

This Use case deals with application development using Swift code. Thus, we would like to share with you, the basics of iOS Swift programming. The following details have been covered in this blog:

  • Installing Xcode 6(Apple has provided Xcode 6 integrated with Swift).
  • How to use Variables, Strings, Array, Dictionary, If statements, Switch statements,Functions in Swift app development.

What we want to do:

  • Prerequisites
  • Open Terminal and install Xcode
  • Execute and study the features of various Swift commands ,functions ,and statements

Solution

Prerequisites

  • Configuration: Check the below configuration requirements into your Mac:
    • OS X Yosemite
    • Xcode 6

Follow the below steps of process

  • Open up a terminal window.
  • If you have two or more versions of Xcode installed, then you will need to select Xcode 6 as your default version. If you are only running Xcode 6, then skip ahead to step II, otherwise go ahead and run step I:
    • Step I:    sudo xcode-select -s /Applications/Xcode6.app/Contents/Developer/
    • Step II:   xcrun swift

Variables

As with every programming language, you have variables which allow you to store data. In Swift, you declare variables with the ‘var’ keyword and constants using the ‘let’ keyword. Here is an example:

The above code instructs the system that, you want to create a variable named ‘mywords’ which is of type String containing the text, “Hello World”.

Variables can be modified once created. So here, we can change our mywords variable by assigning a different string to it.

While coding an application, there are many instances where you don’t want to change a variable once it has been initialized. Apple has always had two variants of types mutable and immutable. Mutable, meaning the variable can be modified and immutable, that cannot be modified. They prefer immutability by default, which means that the values aren’t going to change and it makes our app faster and safer in a multi-threaded environment. To create an immutable variable you need to use the keyword let.

If you change your greeting example to use ’let’ instead of ‘var’, then the second line will give you a compiler error because you cannot modify greeting.

  • The correct use of let

  • NOTE : In Objective C,you need to end each statement in your code with a semicolon. If you forget to do so, it will throw a compilation error. As you can see from the above examples, Swift doesn’t require that you write a semicolon (;) after each statement, though you can still do so if we would like to.

Strings

In Swift, strings are represented by the String type, which is fully Unicode-compliant. You can declare strings as variables or constants.

Check below, to see how two strings can be concatenated using the ‘+‘ operator:

Arrays

The syntax of declaring an array in Swift is similar to that in Objective C. Here is an example:

Objective C:

Swift :

To access an item from the array you need to use the subscript:

Simply use the count method to find out the number of items in the array:

Dictionary

A dictionary allows you to store key-value pairs and access the value by providing the key. Here is an example:

If statement

To control the flow of our code, we of course have an If statement. Find an example below:

Switch Statement

The Switch statement in Swift is very versatile and has a lot of features. But we should follow some basic rules while using the switch statement:

Note:

  • There is no need for a break statement after each case statement.
  • The switch is not limited to integer values. You can match against any values such as String, Int, Double or any object for that matter.

Functions

Swift programming functions can be created by using the “func” keyword.

We can also pass single and multiple parameters to print any values.

E.g. single parameter passing

E.g. multiple parameters passing

Classes

In Objective C, you create separate interface (.h) and implementation (.m) files for classes. Swift no longer requires developers to do that. You can define classes in a single file (.swift) without separating the external interface and implementation.
To define a class, you use the class keyword. Here is a sample class in Swift:

Conclusion

In this blog, we have discussed about iOS Swift programming languages basics with latest OS X (Yosemite) and Xcode 6. Using this blog as a base for Swift programming, beginners can develop sample application code for iOS devices in future. In the forthcoming mobile blogs, I will provide explanation on Swift sample application coding with detailed major source code description.

References

3227 Views 9 Views Today
  • Bharath Antony

    Excellent job..

  • André Teunissen

    How to loop through Array < Dictionary > ?

    • http://www.treselle.com/ Treselle Systems Blog

      Here is an example that shows 2 loops.

      The first one loops through the array picking out each dictionary,pair.The second loop, loops through the dictionary picking out each key,value:

      var people:Array<Dictionary> = [["first":"Saba", "last":"Jones"], ["first":"Joe", "last":"Mano"]]

      // Grab each person dictionary from the array of dictionaries
      for person in people {
      // Grab each key, value pair from the person dictionary
      // and print it
      for (key,value) in person {
      println(“(key): (value)”)
      }
      }

      Output:

      first: Saba
      last: Jones
      first: Joe
      last: Mano

      Note that dictionaries are unordered, so this could also print:

      last: Jones
      first: Saba
      first: Joe
      last: Mano

      • André Teunissen

        Many thanks for this great reply. unfortunately I get the error in line “for person in people” saying “does not have a member called generator”.

        • http://www.treselle.com/ Treselle Systems Blog

          I have made some changes to the above code, Please try the below code :

          let people:Array<Dictionary> = [["first":"Saba", "last":"Jones"], ["first":"Joe", "last":"Mano"]]

          // Grab each person dictionary from the array of dictionaries
          for person in people {
          // Grab each key, value pair from the person dictionary
          // and print it
          for (key,value) in person {
          println(“(key): (value)”)
          }
          }

          • André Teunissen

            It’s working! Changed also the dictionary part to < Dictionary >. Just capitalizing the first letters differently (with spaces for some rendering mistake on the web). Your the best!

  • Harry Martin

    I feel writing code in swift programming language is very interactive and filled with fun, the syntax is concise yet expressive, and apps run lightning-fast. I would suggest you to make use of advanced tutorials for learning swift with this mentioned http://learnsauce.com/appleswifttutorial/ hope you would surely find interesting.