Tuesday, 10 June 2014

iOS Swift Development Tutorials Part II: Deeper into Swift


In the previous article, you/we/I? looked at the very basics of the Swift syntax. In this article , we are gonna look at...



  • Functions.
  • Classes.
  • Objects.
  • Sub Classes.
  • Some of String operations.
  • Some of Array operations.
  •                            


Functions


Functions are declared as so...


func <function_name>( <param1_name> : <-data-type>,  <param2_name> : <-data-type>...) -> returnData-Type
{
    //body
}

A keyword "func" followed by your function name, parenthesis, arguments(and their data-types).
The return data-type and the above part of the function signature is separated by a "->" arrow operator.

Example:


func add( pNo1 : Int, pNo2 : Int) -> Int
{
    return (pNo1 + pNo2)
}
println("ADDITION: \(add(69, 69))")

Output: Addition: 138

Play around with String, Double types if you must.

Functions which accept variable Number of Parameters

Duuuuhhhhhhhh...what? You can create some functions which may accept none, one, two....n number of parameters. 
Such functions accept any number of parameters(even zero). To access all of them inside the function, you will have to iterate through an array...(YES an Array).

Here's a sample:


func mean( parameters : Int...) -> Double
{
    var sum = 0
    for number in parameters
    {
        sum += number
    }
    
    var answer : Double = Double(sum)/Double(parameters.count)
    
    return answer
}
println( "AVERAGE OF 1,3,2,6,0,4,8 IS \(mean(1,3,2,6,0,4,8))" )

Here's what's going on.


  • A function named "mean" accepts any number of arguments, all of type Int.
  • It stores it in an array called parameters.
  • Iterates through the array via fast enumeration.
  • Returns a double value which is the average of all wall arguments passed to it.
  • Profits.

Functions which return multiple objects/variables

You can create functions which may return one, two....n number of parameters. 
These functions return a tuple.


func OSNameVersion () -> (String, Double)
{
    return ("MAC OS X", 10.9)
}
println("\(OSNameVersion())")

Output: (MAC OS X, 10.9)



Classes


The blueprint which holds all kinds of data, be it variables or  functions.
Here's how classes are created...


class <class_name>
{
     //member functions, variables
     init()
     {
            //variable initialisations
     }
}


Example:

class Animal
{
    var name : String
    var myNumber = 1
    
    var numberOfLegs : Int
    
    init(pName: String, pLegs: Int)
    {
        self.name = pName
        self.numberOfLegs = pLegs
        
        println("NAME IS "+"\(self.name)" + " AND NUMBER OF LEGS IS " + "\(self.numberOfLegs)")
    }
    
    func description()
    {
        println("THIS IS THE BASE ANIMAL CLASS")
    }
    
}

IMPORTANT:  

  • A Class must have an initialiser. This is done by implementing the ""  function. (Objective-C coders already know this. Java/C++ guys better know these as Constructors).
  • You HAVE to initialise all your class variables (or properties rather) either in the "init", or while declaring them as above (look at myNumber).
  • the init is what it says it is, an initialiser. Its main purpose is assigning initial values to properties.
  • Objective-C guys already know what self is. Java guys, look at this.
  • "name" and "myNumber" are properties. Objects of this class will set and get these properties using the dot(.) operator.

Objects


Now that we know how a class are made, lets instantiate it. Create an object of a class like so...


var <Object_name> = <Class_name>(<argument_name> : <data-type>...)


IMPORTANT: The number and data type of argument(s) in the above syntax should exactly match the Class' init.  

Example:


var man = Animal(pName: "Man", pLegs: 2)
var dog = Animal(pName: "🐶", pLegs:  4)

^YES you saw that dog emoticon correctly, try it in Xcode ;]

Accessing Properties of the object:

To access( and possibly print ) the properties of the object...


println("NAME IS "+"\(man.name)" + " AND NUMBER OF LEGS IS " + "\(man.numberOfLegs)")

So its like...

Set:

<Object_Name>.<Property_name> = _value

Get:


<Object_Name>.<Property_name>

Calling class functions:


<Object_Name>.<Function-Name>(<arguments>)

SubClasses


Subclasses extend the functionality of existing classes. Here's The syntax of creating one...


class <subClass_name> : <baseClass_name>
{
     //properties
    
     //override base class functions (optional)

     //init

}


Example:

class Dog : Animal
{
    var skill : String;
    
    override func description()
    {
        println("THIS IS THE DOG SUBCLASS AND ITS SKILL IS \(self.skill)")
    }
    
    init(pSkill: String)
    {
        self.skill = pSkill
        super.init(pName: "Dog", pLegs: 4)
    }
}

var dogVar = Dog(pSkill: "Sense Of Smell")
dogVar.description()


Here's what's happening...


  • Subclass named Dog which extends "Animal" class.
  • A property of "Dog" class called "skill".
  • Look at the "Animal" class in this article above. It had a function called "description". "Dog" overrode it, as in.. changed it according to its own rules.
  • init. More or less compulsory. 
  • super.init() is absolutely compulsory. It is basically the parent/base class initialiser. You HAVE to initialise base class properties as well.
  • An object called dogVar, with data-type Dog, using the same signature as the init.
  • A call to the description function of Dog class;

Feel free to make some of your own classes,  objects, properties and mess around.


Some String and Array operations


There are a gazillion things you can do with Strings and Arrays, according to your requirements.
I'm gonna list some commonly used stuff.


String Comparision:

Objective-C guys use isEqualToString method, Java people use .equals().

Swift directly compares Strings using the == comparison operator. :]


var firstString = "You like to think you are never wrong!"
var secondString = "You have to act like you're someone!"

if firstString == secondString
{
    println("HELL YEAH! EQUAL STRINGS!")
}
else
{
    println("OH DANG! UNEQUAL STRINGS!")
}




String Interpolation:

To avoid TL;DR, lemme just post a sample....


var timesBetter = 2
println("GTA V IS \(Double(timesBetter)) times better than WATCH DOGS")

Output:
GTA V IS 2.0 times better than WATCH DOGS


What happened there?


  • The \() will add there value of the object inside its parenthesis.
  • Initially the timesBetter variable is an Int, but Double(timesBetter) converts it into a double. Works for other data-types as well. Hence the replaced value is 2.0 .


String Prefixes, Suffixes:

Use .hasPrefix  and .hasSuffix...


var myString = "You Win!"

if myString.hasPrefix("You")
{
    println("Prefix \"You\" exists")
}

if myString.hasSuffix("Win!")
{
    println("Suffix \"Win!\" exists")
}

Conversion to upper or lower case:


var testString = "HaTerS Be LiKe... \"LeL ThiS iS So SImpLE WhY YoU gottA makE a TutoriaL AbouT thIS\""

println( "UPPERCASE: \(testString.uppercaseString)")
println( "LOWERCASE: \(testString.lowercaseString)")


Adding an object to an already created array:

Objective-C guys used addObject: while Java coders use .add().

Here, use .append()


var platformArray = ["PS3", "X360"]
platformArray.append("XB-ONE")
//New Array is ["PS3", "X360", "XB-ONE"]

^This adds "XB-ONE" as the last element of the array.

Adding an object to an already created array at a particular index:

var platformArray = ["PS3", "X360"]
platformArray.insert("XB-ONE", atIndex: 1)

//New Array is ["PS3", "XB-ONE", "X360"]

^This adds "XB-ONE" at index 1 of the array.

Remove objects from Arrays:

For removing an object at an index, use .removeAtIndex()

var platformArray = ["PS3", "X360"]
platformArray.removeAtIndex(1)

//New Array is ["PS3"]

^This removes the object at index 1 of the array.


For removing the last object, use .removeLast()



var platformArray = ["PS3", "X360"]
platformArray.removelast()

//New Array is ["PS3"]



For emptying the Array, use .removeAll()

var platformArray = ["PS3", "X360"]
platformArray.removelast()

//New Array is ["PS3"]




For getting array count, use .count property


var platformArray = ["PS3", "X360"]
println("\(platformArray.count)")

//Output will be 2



There are innumerable properties and functions available for both Strings and Arrays.

I cannot list them all, mainly cuz I'm lazy, but here's the complete list...

https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/SwiftStandardLibraryReference.pdf


AND NOW THE BIG ONE: A mixture of everything.



class Movie
{
    var name : String = ""
    var rating : Int = 0
}

class MainClass
{
    var movies : Array<Movie> = []
    
    func addNewMovie( pName: String, pRating: Int )
    {
        var movie = Movie()
        movie.name = pName
        movie.rating = pRating
        self.movies.append(movie)
    }
}

var mainClassVar = MainClass()
mainClassVar.addNewMovie( "Van Helsing", pRating: 2)
mainClassVar.addNewMovie( "Inception", pRating: 5)
mainClassVar.addNewMovie( "Zero Dark Thirty", pRating: 4)


//PRINT OBJECT ARRAY
println("MOVIE ARRAY: \(mainClassVar.movies)")

//PRINT EACH
for tempMovie in mainClassVar.movies
{
    var movieCastVar = tempMovie as Movie
    println("NAME: " + "\(movieCastVar.name)" + ", RATING: " + "\(movieCastVar.rating)")
}


STEP BY STEP HEART TO HEART...

  • A class called Movie, used to represent a movie instance.
  • Movie has 2 properties, name and rating, both initialised while declaration, so no need of an initialiser.
  • Another Class called MainClass, containing a property array called movies, initially empty.
  • movies will only contain objects of data-type Movie, the class created previously.
  • A member function, called addNewMovie, which takes in a name String and a rating Int.
  • addNewMovie on being called, creates a Movie instance, sets their properties to the arguments passed to it and finally adds that instance to its own array movies.
  • An object of MainClass, called mainClassVar which calls addNewMovie thrice, passing different parameters.
  • Iteration through the movies array property of mainClassVar via fast enumeration.
  • The temp variable inside for is cast as type Movie, else you would not be able to access its properties obviously.


Well thats it for this article. In the next part, I would look into actually making a sample app using Swift.
Peace!



Monday, 9 June 2014

iOS Swift Development Tutorials Part I: A Sneak Peak at what's Swift all about!


This is my first attempt EVER to post a tutorial blog so just bear with me :P
Criticism(constructive/destructive/troll) is most welcome.

You probably know what Swift is since you are here but still here's a quick intro...

Swift is a programming language newly announced by Apple at the WWDC 2014. Swift will/can be used for developing iOS as well as Mac OS X applications, which were previously developed in Objective C/ Objective C++. 

Also announced was iOS 8. Apps developed in Swift would work with iOS 7 and 8. Swift can be used in conjunction with Objective-C. I'll probably talk about that in future articles...probably being the key word there.

  • To code in Swift for iOS/ Mac OS X, you need to download Xcode 6 Beta from Apple Developer.
  • Here's the link: https://developer.apple.com/xcode/downloads/
  • If you are only interested in learning the language without any of the app sandbox stuff, follow these steps
    • After installing Xcode 6, Go to File->New->Project.
    • Select Application under OS X front he left panel.
    • Choose "Command Line Tool" -> Next.
    • Enter the project name, Choose Language as "Swift" obviously. -> Next.
    • Select Location. -> Finish.
    • Profit.





You probably know about Objective C, its syntax blah-blah...If you don't, you're probably better off learning that first. Also ...

BOOOOOOOOAAARING!


Enough with the technical blah-blah...Lets get to the action.

I'm assuming you are familiar with Cocoa Touch frameworks or at least some of them, and you have an idea about Objective-C syntax, or at the very least some idea about programming and its concepts C'mon.  Even if you don't, and you are an aspiring iOS developer, you need to know what Swift is all about. So read on...it won't hurt...probably.


Getting Started: THE VARIABLE

The root of all temporary/permanent storage of values inside the code..
ALL HAIL THE MIGHTY "variable".

Declarations:


var myNumber = 1

Objective-C coders must be thinking "BOOOO! Wheres the semicolon? Wheres the data-type?
Well, there's no need of those anymore.

Although in some cases you do have to mention them. Here's how...


var name : String

The above code declares a variable named "name" of type String (Objective-C uses NSString).

However, the following code generates an error...

var myVariable

The compiler thinks...WTF? How do I know what type it is? ERROR!
So either you gotta assign it a value like...


var myVariable = 1

OR


var myVariable = 2.0

OR


var myVariable = "WOW THIS IS EASY"

All the three declarations are correct. They tell the compiler if "myVariable" is an int, double or String respectively. (Objective-C coders may notice the lack of @ before quotes.

Alternatively, specify its data-type if you don't wanna initialise it like so...


var myVariable : Int

So, in short its like...

var <userDefinedName> : <data-type>


Constants

Constant variables are declared using a keyword called "let"as...


let myConstant : Int = 10

Same works for strings, double etc.

<Quick-Tip> Data types now begin with a Caps letter


Arrays

Arrays are declared as...


var platforms  =  ["PS3", "X360"]

OR


var platforms : Array<String> =  ["PS3", "X360"]

This creates an array of two strings. Again, specifying data-type is upto you, but look closely. The second statement has a "< String >" along with the "Array" type. Works for other types too.

This tells the compiler that the array will only contain String data-type. Java coders should already know this.

Dictionaries

For those who dunno, a dictionary is a data-type which associates a key to a value. A key and its value are separated by a colon. A dictionary can have any number of key value pairs.
Kinda like this...

Key : Value

The data type of the value may vary. For more info on this... Google it!


var gamesDict = [
    "name" : "GTA V",
    "rating" : 5,
    "platforms" : ["PS3", "X360"],
    ]


This creates a dictionary variable named "gamesDict" and maps a String, Int and an Array to the respective keys.
All Key-Value pairs are separated by commas, even the last pair.

Accessing a value for a particular key



var gameName = gamesDict["name"] 
var gameRating = gamesDict["rating"] 

This assigns gameName as "GTA V" and gameRating as 5.
While accessing the values as above is fine, the compiler will give you a warning as its unpredictable(to the compiler) what will be the data-type of value for the mentioned key.

So a better way would be...


var gameName = gamesDict["name"] as String

var gameRating = gamesDict["rating"] as Int

^this is sort of a type cast. Be careful with this though. This can cause crashes/errors later if you don't set the type right. When in doubt cast it as "AnyObject". More on that in future parts. Google it if you are impatient!

The above dictionary had values with different data-types. But if you wanna make a dictionary which you know will only have values of a single data-type, or you don't wanna allow any other type to be added, use this...


var gamesDict : Dictionary<String, String> = [
    "name" : "GTA V",
    "rating" : "M"
    ]


Printing on the Console


Use println() function to print Strings on the debug console. Java guys would be familiar.


println("GIMME A HELL YEAH")


For printing variable values, there isn't a % placeholder, instead use a \() like so...



var nOne = 2
var nTwo = 5

var sum = nOne + nTwo

println("Addition is \(sum)")

This would print "Addition is 7"

Conditions: if...else block


var nOne = 2

if nOne > 0
{
    println("less than zero")
}
else
{
   println("greater than zero")
}

A notable difference is no parenthesis required for the if condition check. Ofcourse the curly brackets are needed if the if or else block have more than a single line DUH.

The FOR statement


var games = ["GTA V", "WATCH DOGS", "SUPER MARIO"]

There are many ways of looping through the above array...


for temp in games
{
    println("GAME NAME: \(temp)")
}
^temp is any temporary variable created by us.



for i in 0..3
{
    println("GAME NAME: \(games[i])")
}
^this is equivalent to i being initialised as 0 first. and incrementing by 1 until 2.
3 is not included.
Array elements are accessed by array_name[i] where i is an integer index.



for( var i = 0; i < 3; ++i)
{
    println("GAME NAME: \(games[i])")
}
^good ol' standard for Statement we all know and love.

All of the above print the three strings in the games array one after another(on a new line obviously).

The WHILE statement


var n = 100

while n < 0
{
    n = n + 10
}

The SWITCH statement


var platforms  =  ["PS3", "X360"]

for platformVar in platforms
{
    switch platformVar
    {
        case "PS3":
            println("Playstation Supported!")
        case "X360":
            println("Xbox 360 Supported!")
        default:
            println("No Console Version!")
    }
}

^Again, no parenthesis needed,  Iterate through the array via temp variable,  check its value via switch statement, and print accordingly. 
And Yes, Switch works on String variables too. ^_^


Well thats it for this part. Soak it in.

In the next article, Its Functions, Classes, SubClasses and Objects.

Feel free to copy and mess around with the snippets in Xcode. Lemme know if there are errors.

Peace!