iOS Swift Tutorial

Swift Programming Language

Swift is the new programming language from Apple for developing IOS Apps. I must agree that its lot easier for a newbie to get started with Swift than Objective-c. Here are a few things which I found interesting

Named Parameters

Here are the two ways how you can implement area function

func area(height : Int,width: Int) -> Int {
  return height * width;
}

let calculatedArea = area(10,20)
println("Area : \(calculatedArea)")
Area : 200

Lets implement the same area function using named parameter

func areaNamedParameter(#height : Int,#width: Int) -> Int {
    return height * width;
}
let calculatedAreaParametered = areaNamedParameter(height:50, width:20)
println("Area : \(calculatedAreaParametered)")
Area : 1000

One more example is to return tuple and named tuples

A tuple type is a comma-separated list of zero or more types, enclosed in parentheses.
Tuple can be used to return multiple values from a function and we can also name the returned tuple
so that we can dereference the value by using the name. Lets write a simple function to convert a
hash to a named tuple.

func hashToTuple(myhash: [String:String]) -> (title:String?, name:String?) {
    return (title: myhash["title"],name:myhash["name"])
}

let data = hashToTuple(["title":"Software Engineer","name":"Shrikar"])

if let title = data.title {
    println(title)
}

if let name = data.name {
    println(name)
}

Software Engineer
Shrikar

let dataPartial = hashToTuple(["title":"Software Engineer"])
if let title = dataPartial.title {
    println(title)
}

if let name = dataPartial.name {
    println(name)
}
Software Engineer

String Optionals

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.

Some places optionals are useful:

  • When a property can be there or not there, like middleName or spouse in a Person class
  • When a method can return a value or nothing, like searching for a match in an array
  • When a method can return either a result or get an error and return nothing
  • Delegate properties (which don’t always have to be set)
  • For weak properties in classes. The thing they point to can be set to nil
  • For a large resource that might have to be released to reclaim memory

Lets take an example

func returnOptional(parameter: String) -> String? {
    if parameter == "iOS"{
        return "Awesome"
    }
    else {
        return nil
    }
}

The above function will return “Awesome” if we pass “iOS” and nil otherwise.

let retdata = returnOptional("iOS")
if let newdata = returnOptional("iOS") {
    println(newdata)
} else{
    println("Not cool")
}
Awesome

Optional Chaining

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

This implementations looks a lot cleaner in converting the returned value to lowercase depending on what optional is returned.

let retdata = returnOptional("iOS")
if let newdata = returnOptional("iOS")?.lowercaseString {
    println(newdata)
} else{
    println("Not cool")
}

awesome

if let newdata = returnOptional("Some Random OS")?.lowercaseString {
    println(newdata)
} else{
  println("Not cool")
}

Not cool

This is not a complete list of some interesting features so please feel free to comment and I will add those to the list above.

I used Treehouse to learn swift. I strongly recommend to try it out if you want to get started with iOS and Swift. Here are the links Non Affiliate link Affiliate link

About the author

Shrikar

Backend/Infrastructure Engineer by Day. iOS Developer for the rest of the time.