Monday, September 28, 2015

Swift: Type Casting

This tips and tricks explains how to perform upcasting and downcasting in Swift, using the as, as!, and as? keywords.

Keywords

Swift 2.0, type casting, as, as!, as?

Solution

Upcasting using as

Upcasting happens when you are trying to cast from a derived class to a base class. This will always succeed. The following is an example using the as keyword to perform upcasting:

        let btn = UIButton()
        let view = btn as UIView

The as keyword can also be used for literal casting:

        let strNum1 = 2.4 as Float
        let strNum2 = 2.4 as Int

Downcasting using as?

Downcasting happens when you are trying to cast from a base class to a derived class. This may not always succeed.

Consider the following code snippet:

    @IBAction func btnClicked(sender: AnyObject) {
    }

In this action for a Button view, you have an argument named sender of type AnyObject. If you want to cast this to a UIButton, you may attempt to use the as keyword:

    @IBAction func btnClicked(sender: AnyObject) {
        let btn = sender as UIButton
    }

However, the compiler will flag this as an error as the type casting may fail. Instead, you have to use as? keyword to perform a downcast, like this:

    @IBAction func btnClicked(sender: AnyObject) {
        //---downcasting---
        let btn = sender as? UIButton
        print(btn?.titleLabel?.text)
    }

The as? keyword tries to perform a downcast, and returns a value of the specified type if it succeeds, or nil if it fails. Hence, the result of the above casting is a UIButton? (optional). To use the btn constant, you need to unwrap it using the ? ( or !) operator.

A safer way to deal with downcasting is to wrap it using the if let statement, like this:

    @IBAction func btnClicked(sender: AnyObject) {
        //---downcasting---
        if let btn = sender as? UIButton {
           //---casting succeeds---  
           print(btn.titleLabel?.text)        
        } else {
           //---casting failed---           
        }
    }

Notice that using the if let statement you now don’t have to unwrap the btn constant as it is now a UIButton and not UIButton?.

Downcasting using as!

If you are very sure that the casting will always succeed, you can use the as! keyword, like this:

    @IBAction func btnClicked(sender: AnyObject) {
        let btn = sender as! UIButton
        print(btn.titleLabel?.text)       
     }

The result of the casting is a value of type UIButton. However, if you are not careful, and the casting fails, it will crash your app:

    @IBAction func btnClicked(sender: AnyObject) {
        //---casting will fail and your app will crash!---
        let tableView = sender as! UITableView       
     }

When using the as! keyword, you can also specify the destination type to be an optional, consider the following:

        var dict = [Int:Any]()
        dict[1] = "Gold"
        dict[2] = "Silver"
        dict[3] = "Bronze"
       
        print(dict[1] as! String)  //---Gold---
        print(dict[1] as! String?) //---Optional("Gold")---


The last statement converts the specified item in the dictionary to a String? (optional).

Sunday, September 27, 2015

Team Building Activities


To build great teams in your organization, participating in a team building activity is an excellent way to strengthen and enhance the understanding and camaraderie of team members. At Developer Learning Solutions, it is our firm belief that learning should both be fun and engaging. That’s why we have developed a series of interesting and fun team-building activities that cater to different types of audiences. From indoor activities like 3D printing to outdoor activities like Geocaching, each activity type serves to impart new knowledge as well as foster greater understanding between teams.

List of Activities



Fun with 3D Printing!
In this fun activity, teams will learn about the basics of 3D printing and how it works. Teams will then be tasked to design an object using user-friendly 3D design software. Each team will need to print their design using the provided 3D printer. The team with the most creative design is the winner!


Fun with Electronics!
Each team is assigned a set of littleBits, a library of modular electronic components that snap together with small magnets for prototyping and learning. Using littleBits, teams can build interesting and exciting electronic projects without any programming knowledge.

With littleBits, your creativity is the only limit on what you can build. Each team will first experiment with littleBits, and then work on a given challenge to build a specific project within a given time frame. The team with the most creative and robust solution is the winner!


Domino Challenge


The building and toppling of domino stones is a great way to build the camaraderie of your teams. Teams are supplied with domino stones and need to design and build a domino setup around a specific theme. The team with the most creative and interesting setup is the winner!


Fun with 3D Doodling!

In this fun event, teams will learn how to doodle with the 3Doodler 2.0 pen. Using the Doodler pen, you can doodle in 3D without the need to use software or computer. Using purely your imagination, you can now think, dream, and create in 3D using the 3Doodler 2.0 pen. Teams will then be tasked to design an object using the 3Doodler 2.0 pen. The team with the most creative design is the winner!

Geocaching
This activity requires teamwork, strategic planning, and effective communication to complete. Using a mobile device, teams must locate the position of various points-of-interest (POI).

For this event, each team will provide a mobile device (iPhone or Android). During the briefing, each team will install a mobile application on the device. The mobile application will list the POIs that the team needs to locate within the given time duration. The scoring will be based on the following factors:
·      The time taken to locate each POI
·      The number of hints needed to locate each POI


Sphero Challenge
The Sphero is a spherical robot that is controlled by either a smartphone or tablet. Teams will need to design and create mazes for the competing teams to use their Sphero to navigate through. The team whcich clears the maze in the shortest amount of time is the winner!


Download the brochure for more details of each activity.
Contact Wei-Meng Lee (weimenglee@learn2develop.net) for a quotation.

Friday, September 25, 2015

IOT103 – 1-Day Programming littleBits using Arduino - 30 Dec 2015

In this course, participants will how to prototype electronic projects without messing with breadboards and jumper wires. Once the prototype is built, they will learn how to interface with Arduino programmatically.
Course Fee
S$1097 (nett; no GST)
Schedules
Start DateEnd DateDetailsCategory
Wed Dec 30 2015Wed Dec 30 2015PDF
The course fee includes the Arduino Coding Kit
Venue
Bayview Hotel Singapore
30 Bencoolen Street
Singapore 189621  

If your company requires in-house training, you can contact us to customize the topics to meet your training requirements. We train worldwide! We have conducted customized classes in the United States, Canada, Norway, Denmark, Japan, China, Hong Kong, Taiwan, and Thailand. 

Saturday, September 05, 2015

Tip - Swift 2.0 - Converting Keys and Values in a Dictionary into Arrays

Very often, you need to extract keys and values stored within a dictionary as arrays. Here's how to do it:

//---declare a dictionary---
var stocks = Dictionary<String, Double>()

//---populate the dictionary---
stocks["AAPL"] = 109.15
stocks["MSFT"] = 42.97
stocks["GOOG"] = 603.00

//---extract the keys as an array---
let symbols = Array(stocks.keys) //["AAPL", "GOOG", "MSFT"]

//---extract the values as an array---
let prices = Array(stocks.values) //[109.15, 603, 42.97]

Friday, September 04, 2015

IOS302 - Apple Watch Programming Course - 17 Sep 2015

In the upcoming Apple Watch Programming course, I will cover the latest watchOS 2.0!

Apple's latest watchOS 2.0 will support:

    * Complications and Time Travel
    * The new Watch Connectivity Framework
    * New execution model for apps
    * Several new controls like Picker, Alerts and Action Sheets, and Movie control
    * The ability to access the hardware on the Apple Watch
Course Fee
S$1397 (nett; no GST) Includes an Apple Watch Sport
Get a copy of my Learning WatchKit Programming book when you attend the course.
If your company is sponsoring you for the training, your company can enjoy 400% tax deductions/ allowances and/or 60% cash payout for investment in innovation and productivity improvements under the Productivity and Innovation Credit (PIC) scheme. For more details, check out the Productivity and Innovation Credit page. 
Schedules
Start DateEnd DateDetailsCategory
Thu Sep 17 2015 CONFIRMEDThu Sep 17 2015PDF
Venue
Bayview Hotel Singapore
30 Bencoolen Street
Singapore 189621