Showing posts with label let. Show all posts
Showing posts with label let. Show all posts

Saturday, November 19, 2016

Swift Tip - Using the guard statement

Very often, in your app you need to check if multiple variables are non-nil before you can perform some processing. For example, the following example shows that you can use the if statement to verify that both the credit card no. and expiry date is non-nil before you validate the credit card:

    func validatePayment(creditCardNo:String?, expiry:String?){
        if let cc = creditCardNo {
            if let exp = expiry {
                print("Validating credit card...")
                //...
                return
            }
        }
        print("Missing Credit Card No. or Expiry Date")

    }

However, the nesting of multiple if statements makes your code really unwieldy. A better way is to use the guard statement, like this:

    func validatePayment(creditCardNo:String?, expiry:String?){
        guard let cc = creditCardNo, let exp = expiry
        else {
            print("Missing Credit Card No. or Expiry Date")
            return
        }
        //---validate credit card---
        print("Validating credit card...")

    }

The guard statement ensures that both statements (let cc = creditCardNo and let exp = expiry) are true; else it will execute the else block.

The following shows the output of the function with the following combinations of arguments:

        //---Missing Credit Card No. or Expiry Date---
        validatePayment(creditCardNo: nil, expiry: "11/21")
        validatePayment(creditCardNo: "1234567890123456", expiry: nil)
        validatePayment(creditCardNo: nil, expiry: nil)
        
        //---Validating credit card...---

        validatePayment(creditCardNo: "1234567890123456", expiry: "11/21")

Wednesday, June 04, 2014

The Swift Programming Language - Lesson #2 - Arrays

In this lesson, you will learn how to create and use arrays in Swift.

Arrays

An array is a collection of objects - and the ordering of objects in an array is important. The following statement shows an array containing 3 items: 

var OSes = ["iOS", "Android", "Windows Phone"]

In Swift, you create an array using the [] syntax. The compiler automatically infers the type of items inside the array; in this case it is an array of String elements.

Note that if you attempt to insert an element of a different type, like this:

var OSes = ["iOS""Android""Windows Phone", 25]

The compiler will assume the elements inside the array to be of protocol type AnyObject (which is similar to id in Objective-C and System.Object in .NET), which is an untyped object.

In general, most of the time you want your array to contain items to be of the same type, and you can do so explicitly like this:

var OSes:String[] = ["iOS", "Android", "Windows Phone"]

This forces the compiler to check the types of elements inside the array and flag an error when it detects otherwise.

The following example shows an array of integers:

var numbers = [0,01,2,3,4,5,6,7,8,9]

To retrieve the items inside an array, specify its 0-based index, like this:

var item1 = OSes[0]   // "iOS"
var item2 = OSes[1]   // "Android"
var item3 = OSes[2]   // "Windows Phone"

To insert an element at a particular index, use the insert() function:

OSes.insert("BlackBerry", atIndex: 2)

item3 = OSes[2]       // "BlackBerry"
var item4 = OSes[3]   // "Windows Phone"

Note that in the above function call for insert(), you specify the parameter name - atIndex. This is known as an external parameter name and is usually needed if the creator of this function dictates that it needs to be specified.

We shall talk more about this when we discuss functions. 

To change the value of an existing item in the array, specify the index of the item and assign a new value to it:

OSes[3] = "WinPhone"

To append an item to an array, use the append() function:

OSes.append("Tizen")

Alternatively, you can also see the += operator to append to an array, like this:

OSes += "Tizen"

You can append an array to an existing array, like this:

OSes += ["Symbian", "Bada"]

To know the length of an array, use the count property:

var lengthofArray = OSes.count

To check if an array is empty, use the isEmpty() function:

var arrayIsEmpty = OSes.isEmpty

You can also remove elements from an array using the following functions:

OSes.removeAtIndex(3)              // removes "WinPhone"
OSes.removeLast()                  // removes "Bada"

OSes.removeAll(keepCapacity: true) // removes all element

For the removeAll() function, it clears all elements in the array. If the keepCapacity parameter is set to true, then the array will maintain its size.

Mutabilities of Arrays

When creating an array, its mutability (its ability to change its size after it has been created) is dependent of you using either the let or var keyword. If you used the let keyword, the array is immutable (its size cannot be changed after it has been created) as you are creating a constant. If you used the var keyword, the array is mutable (its size can be changed after its creation) as you are now creating a variable.

OK for today! Look out for the next lesson soon!

Tuesday, June 03, 2014

The Swift Programming Language - Lesson #1

Apple has surprised quite a number of developers at WWDC 2014 yesterday with the announcement of a new programming language - Swift. The aim of Swift is to replace Objective-C with a much more modern language and at the same time without worrying too much about the constraints of C compatibility. Apple itself touted Swift as the Objective-C without the C.

For developers already deeply entrenched in Objective-C, it is foreseeable that Objective-C would still be the supported language for iOS and Mac OS X development in the near and immediate future. However, signs are all pointing that Apple is intending Swift as the future language of choice for iOS and Mac development.

While groans can be heard far and near about the need to learn another programming language, such is the life of a developer. The only time you stop learning is when the end of the world is near (OK, you get the idea). So, in the next couple of weeks and months, I am going to walk you through the syntax of the language in bite-size format (so that you can probably read this on the train or on the bus home), and hopefully give you a better idea of the language.

So, let the journey begin!

Constants

In Swift, you create a constant using the let keyword, like this:

let radius = 3.45
let numOfColumns = 5

let myName = "Wei-Meng Lee"

Notice that there is no need to specify the data type -  they are inferred automatically. If you wish to declare the type of constant, you can do so using the : operator followed by the data type, like this:


let diameter:Double = 8;

The above statement declares diameter to be a Double constant. You want to declare it explicitly because you are assigning an integer value to it. If you don't do this, the compiler will infer and assume it to be an integer constant.

Variables

To declare a variable, you use the var keyword, like this:

var myAge = 25
var circumference = 2 * 3.14 * radius

Once a variable is created, you can change its value:

circumference = 2 * 3.14 * diameter/2

In Swift, values are never implicitly converted to another type. For example, suppose you are trying to concatenate a string and the value of a variable. In the following example, you need to explicitly use the String() function to convert the value of circumference to a string value before concatenating it with another string:

var strResult = "The circumference is " + String(circumference)

Including Values in Strings

One of the dreaded tasks in Objective-C is to insert values of variables in a string. In Swift, this is very easy using the \() syntax. The following example shows how:

var strName = "My name is \(myName)"

You can also rewrite the earlier statement using the following statement:

var strResult = "The circumference is \(circumference)"

OK for now, stay tuned for the next lesson!