Click here to Skip to main content
Click here to Skip to main content
Go to top

Introduction to Swift

, 7 Aug 2014
Rate this:
Please Sign up or sign in to vote.
Swift is a brand new programming language which was revealed by Apple at WWDC 2014 along with iOS 8. It is set to eventually replace the Objective – C language which is currently being used for Apple development. Swift is easier to learn and it has got a much cleaner syntax as compared to Obje

Swift is a brand new programming language which was revealed by Apple at WWDC 2014 along with iOS 8. It is set to eventually replace the Objective – C language which is currently being used for Apple development. Swift is easier to learn and it has got a much cleaner syntax as compared to Objective – C. The syntax of Objective – C was very different compared to what you may be used to if you have previous experience with Java, C#, Javascript etc. With Swift, the syntax will seem a bit similar if you have previous web development experience.

Swift is designed to work alongside Objective – C programs. You can add swift code to your existing applications and it will work fine with the existing Objective – C code. If you are new to iOS development, then you can easily start learning Swift although some knowledge of Objective – C may also be helpful as there are a lot of existing libraries which are already written in Objective – C. But Swift is definitely the language for the future and it will slowly replace Objective – C. Along with the language, Apple also released a Swift programming guide which gives a detailed walk through of the language. In this post, i will briefly give an introduction to basic Swift syntax.

What you need ?

To write Swift programs, you need Xcode 6 which is currently in beta. When Swift was announced, Xcode 6 beta was only available for download to developers who had paid apple developer accounts. But as of now, Xcode 6 beta 3 (version as of time of writing this article) is available for free download for anyone having a registered apple account.

Apple has introduced a new feature called “Playgrounds” which lets you try out Swift code and see the result in real time without compilation overhead. As you add code to the playground, you will see the result appear immediately. It is a great way to see the result of some Swift code before adding it to your main application.

To use the code in the example, Install XCode 6 beta on your Mac. Run the application, Go to File -> New -> Playground. Give a new name of the file and you are ready to get started

Variable & Constant

You can define variables in your application using the below syntax

 

var myVariable = 1
var myString = "Hello World"
let myConstant = 12.2

 

You can use the “var” keyword to declare variables that can be changed while the “let” keyword lets you define constants who value can be instantiated only once. If you want to have a variable that can be changed, use “var” to declare it else use “let” to define a constant.

You may have also noticed that we are not specifying the type of the variable. If we don’t specify a type, the compile automatically uses ‘Type Inference’ to deduce the type automatically based on the value. We can also specify the type explicitly using the below format

 

var myInteger : Int = 2
var myDouble : Double = 65.65
var myString : String = "Hello"
var myBool : Bool = false

 

One more thing you will notice is that unlike Objective – C, we don’t have to add semicolon ‘;’ after each statement.

Basic string manipulation is quite simple. You can use the “+” operator to concatenate the two strings

 

var myString1 = "Hello"
var myString2 = "Madhur"
var concatenateString = myString1 + myString2

 

The above code will concatenate the two strings.

Arrays

Arrays can be defined in Swift as shown below

 

var myArrayOfInt = [12,23,2,4,5]
var myArrayOfString = ["Ab","Cd","Ef","Gh"]
//You can also define the array explicitly
var myArrayOfInt : Int[] = [12,23,2,3,1]

 

You can access any specific array item using its index

 

var myItem = myArrayOfInt[1]

 

you can modify any item by using below

 

myArrayOfItem[2] = 56

 

You can use a for loop to iterate through the array items as shown below

 

for number in myArrayOfInt {
println("Number is \(number)")
}

 

This will iterate through the array and print the result in the console. ‘println’ function is used to print the content to the console. The \(number) can be used to pass specific variables to the function which will get replaced by the actual value of the variable. The result displayed will be “Number is 12″ and so on.

You will notice that the “println” output is not displayed on the playground. To view the println output go to “View -> Assistant Editor -> Show Assistant Editor”. In the Assistant Editor, you can see the output under the Console Output.

Dictionaries

Apart from Arrays, Dictionary is another type of collection that Swift provides. As in other languages, a Dictionary allows you to save your data in <key,value> pairs. Each value is associated with a unique key in dictionary. An example is

 

var myDictionary : Dictionary<String,String> = ["ARS" : "Arsenal", "MU" : "Manchester United", "LFC" : "Liverpool"]

 

You can use ‘key’ as an index to read the values from dictionary.

 

var myValue = myDictionary["ARS"]

 

You can use almost the same syntax for assigning a new <key,value> pair.

 

myDictionary["WHU"] = "West Ham"

 

You can iterate through the Dictionary using the for-in loop. Here is an example

 

for (code,name) in myDictionary {
println("\(code) - \(name)")
}

 

Functions

You use the ‘func’ keyword to define a function in Swift. The definition is much simpler. Here is an exmaple of a function with no arguments and no return value

 

func myFunction() {
println("My First Function")
}

 

To declare the function with arguments and return type, see the below syntax

 

func sayHello(name : String) -> String {
println("Hello \(name) , Enjoy Learning Swift")
}

 

We pass the arguments “(name : String)” by specifying the argument name and the type. We can pass multiple arguments by separating them with commas. We have specified the return type as string. We can call the function using below syntax

 

myFunction()
println(sayHello("Madhur"))

 

Classes

In Objective – C, we used the “.h” & “.m” files to declare class and separate there declaration and implementation. That is not required in Swift. You can create classes and keep there implementation in the same (.swift) file.

You use the ‘class’ keyword followed by class name to create a new class as shown below

 

class userInfo {
}

 

Here i have defined a new class called userInfo. A empty class is not useful, lets add some properties and methods

 

 

class UserInfo {
var firstName : String
var lastName : String
var age : Int = 5
init() {
firstName = "John"
lastName = "Doe"
}
func printUserInfo() {
println("FirstName: \(firstName)")
println("LastName: \(lastName)")
println("Age: \(age)")
}
}

 

We have defined 3 properties in the class called “firstName, lastName, age”. This is similar to how we define our variables. We also need to specify a default value for the properties. This can be specified at the time of declaration or in the “initialize” function. The “init” function is used to initialize the class properties when the object of the class is created. This is similar to Constructors in other languages. You can also have multiple initialize methods with different overloads as shown below

 

init(firstName : String, lastName : String, age : Int) {
self.firstName = firstName
self.lastName = lastName
self.age = age
}

 

We have created an overload of the ‘init’ method which takes three arguments to assign the value of properties. The ‘self’ is similar to ‘this’ pointer in other languages and it refers to the current object on which the initializer is called. We create an object of the class as shown below

 

var user1 = UserInfo()
// Create a class object with properties initialized with default values
var user2 = UserInfo(firstName : "Madhur", lastName : "Kapoor", age : 28)
// Create a class object calling the overloaded init method

 

You can also create getter/setter properties inside classes as shown below

 

var FullName : String {
get {
return "\(lastName), \(firstName)"
}
}

 

This will create a FullName read only property containing the getter method which will return the full name of the person. This can be accessed using “user1.FullName” in the code. To call the methods of the class

 

user1.printUserInfo()
user2.printUserInfo()

 

This will call the class methods. You class methods can also contain arguments and return value. This is similar to what we have seen earlier. In my next post, i will discuss some more features.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Madhur Kapoor
Software Developer (Senior) Infosys
India India
Madhur is Senior Software Engineer by profession having around 3+ yrs of experience in IT industry working on Microsoft Technologies. Apart from Microsoft Technologies, he also likes to work on Mobile Development in Android and Windows 8.
 
His Technical expertise include C#, ASP.Net, WCF, MVC, Linq, Javascript
 
Apart from coding, he like to play Xbox Games, strum guitar or read books.
 
My Blog : http://www.codingparadox.com

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 7 Aug 2014
Article Copyright 2014 by Madhur Kapoor
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid