Introduction To Swift

Introduction To Swift

Apple has introduced one of the biggest updates to iOS since 2008. But the biggest surprise out of WWDC 2014 was the introduction of a brand new programming language, Swift.

Swift2.0 is a wonderful programming language that has been built from the ground from"Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list". It uses the same APIs that Objective-C does. Or, what you can do in Objective-C, you can do in Swift. It also introduces some new concepts longtime programmers will appreciate and some of which I will cover in this series on Swift.

In this first article of this series, I talk about Swift's philosophy or simply syntax. In the second article, I will zoom into more advanced aspects of Swift, such as optionals, memory management, Functional programming. Hang on to your hats, folks, it's going to be a doozy.

This is the eighth post of our blogger month at Xebia. Every day one of the Xebian post a new blog. You can follow the full series at http://blog.xebia.in/pages/blogger-month-2015/.

Table of content

Variables

To declare a variable in Swift use the keyword var

Swift

var number = 1

Objective-C

int number = 1;

C#

var number = 1;

Javascript

var number = 1;

We can see, how similar the Swift syntax is with other languages, the only Significant difference is that we did not have to use a semi-colon at the end of the declaration.

Constants

We can also declare Constants supported in Swift. It can be declared using the keyword let

Swift

let language = “swift" Or let language: String = "Swift"

Objective-C

NSString  *const language = @"Swift";

C#

const string language = Swift”;

The advantage with Swift is that we can use type inference for constant declaration. Type Inference will be detailed in next section.

Working with variables in Swift is no different from other languages however it’s worth noting that it has an easy method for letting us add values in strings such as

var designers = 4
var developers = 4
var teamSize = "The team has \(designers + developers) members”

Arrays

In Swift we create arrays using brackets [ ] and access their elements by writing the index in brackets.

Swift

var arr = ["Nitin" , "Gupta"]

Objective-C

NSArray *arr = @[@"Nitin", @"Gupta"];

C#

var arr = new[] { "Nitin", "Gupta" };

JS

var arr = ["Nitin" , “Gupta"];

We can get an item from the array using the index

var order = arr[0]

and set the value using

arr[0] = “Nitin"

Syntax for the above tasks is the same in Javascript and C# with the addition of the semi-colon at the end of the statement.

Dictionaries

We can declare dictionaries in Swift by defining key-value pairs. When declaring an empty dictionary we have to define the type of the key and the type of the value.

Swift

var dict = Dictionary<String, String>()

We can also declare and assign values

var dict = ["NIT": "Nitin", "GUP": "Gupta"]

Objective-C

NSDictionary *dict = @{
@"NIT" : @"Nitin",
@"GUP" : @"Gupta"
};

C#

var dict = new Dictionary<string, string>
{
    { "NIT", "Nitin" },
    { "GUP", "Gupta" }
};

To get an item from a Dictionary use

Swift

var entry = dict["NIT"]

Objective-C

NSString *entry = dict[@"NIT"];

C#

var entry = dict["NIT"];

To set or add an item in the Dictionary use

Swift

dict["GUP"] = "Gupta"

Objective-C

dict[@"GUP"] = @"Gupta"

C#

dict["GUP"] = “Gupta";

Type Inference

The main difference with Objective-C is that we did not have to define the type, this is because Swift uses type inference and is able to understand that the type of the variable is a number because its initial value is a number.

However we can also define the type if we wish, like so:

var number: Int = 1

Lets declare a string variable in Swift:

var language = "Swift"

The declaration in Swift looks a lot cleaner and almost identical.

Loops

We’ve already discussed how we can create a collection, lets have a look now at how we can loop through them.
Firstly, the for loop syntax.

for var number = 1; number < 5; number++ {
    //do something
}

As we would expect, we specify a value and increment until the condition is met. Objective-C and C# syntax is almost identical, JS is the same while omitting the type of the variable.

We can also achieve the same result by using the for in variant below:

for number in 1..5{
    //do something
}

Here, Swift does the job of creating the number variable and assigns a value automatically while iterating over the specified value.
1..5 is a half-closed range that includes numbers from 1 to 4.
1…5 is a closed range that includes numbers from 1 to 5.

for city in arr {
  println(city)
}

Swift also provides a while and do while loop that have the following syntax:

while number < 10
{
    println(number)
    number++
}

The variable after the while statement is a boolean and the code will execute when it evaluates to true.

The do while loop behaves the same way but it ensures that our code will be executed at least once before your condition is evaluated.

var number  = 9
do {
   println(number)
   number++
}
while number<10

In the example above we ensure that the number value is displayed before we increase it and evaluate the while statement.

Conditionals

Swift Provide if and switch statements to control the flow in our code.

The if syntax in Swift can have parenthesis, but are optional, so you may use any style you prefer.

if city == "NIT" {
   println("NITIN")
}

or

if (city == "NIT") {
    println("Nitin")
}

if statements can be followed by else if and else

if city == "NIT" {
    println("Nitin")
} else if city == "GUP" {
    println("Gupta")
} else {
    println("Xebia")
}

Switch statements in Swift are followed by a case validation but a break statement is not required as there is no implicit fall-through. This means that once a case has been evaluated to true and executed the next case will not be evaluated.

The default action is however required.

switch city {
    case "NIT":
        println("Nitin")
    case "GUP":
        println("Gupta")
    default:
        println("Xebia")
}

The case can contain multiple values separated by a , or ranges.

As you can see, with Swift you can use NSString in a switch statement which is not possible with Objective-c.

Functions

I believe Functions is quite a large subject to cover within this discussion, but Sure we should at least to have a look at how we can declare and use them.
We can declare a function in Swift using the keyword func

func sayName() {
  println("Patrick")
}

Of course we can pass parameters within the parenthesis specifying a variable name and the type.

func sayName(name: String) {
  println(name)
}

Also we can pass multiple parameters separated by coma ,.

func sayName(name: String, lastName: String) {
  println("\(name) \(lastname)")
}

Finally we can declare functions that return results by adding an arrow -> after the parameters and specifying the return type.

func createName(name: String, lastName: String) -> String {
   return "\(name) \(lastname)"
}

Conclusion

Although we covered only the basics of the language above, it is evident that Swift provides a clean and modern syntax that is quite similar to other popular languages.

Objective-C developers will find a lot of similarities with the language and on top of the Objective-C functionality they can now enjoy features such as type inference, strong typing, no need for header files, generics and a lot more while creating iOS or Mac applications or Games.

Leave a Reply

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