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
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:
Output: Addition: 138
Play around with String, Double types if you must.
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...
IMPORTANT: The number and data type of argument(s) in the above syntax should exactly match the Class' init.
Example:
^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...
So its like...
Set:
Get:
Calling class functions:
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?
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.
For removing the last object, use .removeLast()
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
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!



Thanks for sharing good information
ReplyDeleteiOS app development Online Course Hyderabad