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 the 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 string
s.
var myString1 = "Hello"
var myString2 = "Madhur"
var concatenateString = myString1 + myString2
The above code will concatenate the two string
s.
Arrays
Arrays can be defined in Swift as shown below:
var myArrayOfInt = [12,23,2,4,5]
var myArrayOfString = ["Ab","Cd","Ef","Gh"]
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 the below code:
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 the below syntax.
myFunction()
println(sayHello("Madhur"))
Classes
In Objective – C, we used the “.h” & “.m” files to declare class and separate their declaration and implementation. That is not required in Swift. You can create classes and keep their 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
. An empty class is not useful, let's 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()
var user2 = UserInfo(firstName : "Madhur", lastName : "Kapoor", age : 28)
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. Your 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.