Sublime Text 3 – Vi Keybinding to Exit Insert Mode

While the “escape” key has been the usual norm to exit “insert mode” into “visual mode”, the original vi editor encouraged and heavily used the “ctrl+[” keybinding to exit visual mode. Why should we care? Because “ctrl+[” is a lot closer to the fingers and more ergonomic, while hitting the “escape” key moves the left hand out of the home row position. Of course we assume that you remapped your Caps key to ctrl also 🙂

Here is the entry for the Sublime Text keymap file to bind “ctrl+[” to “escape” into visual mode:

{ "keys": ["ctrl+["], "command": "exit_insert_mode" }

On a sidenote: I cannot think of anyone would need to use the Caps key on a computer keyboard. Context is everything, the Caps key was important in the typewriter days because how else can text be made bold or italic. Capitalizing text was often the norm and it did’t indicate shouting as it does now.

The original vi manual, rather the paper “An Introduction to Display Editing with Vi” by Bill Joy has a very useful and quality tutorial that I have not seen matched even by commercial modern Vim/Vi books. You can get the PDF from the freebsd.org vi docs section here.

Developing iOS 10 Apps with Swift by Stanford

Professor Paul Hegarty of Stanford University teaching Developing iOS 10 Apps with Swift, from Lecture 1, graphite on copier paper, 8.5″ x 11″

The course Developing iOS 10 Apps with Swift by Stanford has been around for a while (about 6 months) free on iTunes:
https://itunes.apple.com/us/course/developing-ios-10-apps-with-swift/id1198467120

Had been following the course since the Objective-C days and it’s time to take the latest version in the same tradition.

Here are the course contents based on the 17 lectures :

1. Introduction to iOS 10, Xcode 8 and Swift 3
2. MVC; iOS, Xcode and Swift Demonstration
3. More Swift and the Foundation Framework
4. Views
5. Gestures and Multiple MVCs
6. Multiple MVCs, View Controller Lifecycle, and Memory Management
7. Error Handling, Extensions, Protocols, Delegation, and Scroll View
8. Multithreading and Text Field
9. Table View
10. Core Data
11. Core Data Demo
12. Autolayout
13. Timer and Animation
14. Dynamic Animation Demo
15. More Segues
16. Alerts and Action Sheets, Notifications, Application Lifecycle, and Persistence
17. Accessibility

Will publish the code like before on Github but this time will put all the projects and assignments in one repository:
https://github.com/sanjibahmad/Developing-iOS-10-Apps-with-Swift

So follow along, if you want, with me and feel free to point out if my code can be improved or if the projects and assignments can be done better 🙂 Good luck!

A Movie for the Weekend: Eureka (2000) Directed by Shinji Aoyama

Naoki and Kozue waiting for the bus
Naoki and Kozue waiting for the bus

I think Eureka is one of those great movies that you want to keep going back again and again.

Without going into a plot summary or possible spoilers, here are my feelings about the movie:

There are events that happen in life that need time to resolve. We may call them life-changing events, they happen whether we like it or not. There is a cycle of head-on collision with anger and frustration at first, then perhaps a period of time needed to make a simple decision to start-over and evolve. The time needed may be short or many years. Eventually we are faced with the decision to evolve, there is no other choice. We may become better human beings – lose our prejudices, care and do what’s needed. Perhaps the definition of such lofty actions also change. Perhaps from a different vantage point, they are the most natural thing to do.

I think the trailer (with it’s theme song Eureka, by Jim O’Rourke) does justice to what you can expect from the movie.

Animation / Breakout: Assignment 5, CS193P, Stanford University (Winter 2015)

The Animation assignment also referred to as the Breakout game is the 5th and final assignment from the CS193P course Developing iOS 8 Apps with Swift from Stanford University. Really happy to have finally finished this assignment. In my opinion this was the most complex of all the five assignments in this course.

Platform: iOS 9
Swift: 2.1

Full source code available here at the Github repository

All the 9 required tasks mentioned in page 2 of the specifications document were completed. Though device rotation is not mentioned as a requirement it does appear as a hint. I didn’t allow device rotation because it seemed to me that it would drastically affect the game play negatively.

The main challenge that I faced in completing this assignment was the nuance of using UIKit Dynamics to make a game. There were numerous issues that I was not fully clear in the beginning on how to implement them. So slowly chipped away each issue one by one before I had a clear picture of how they all fit together.

I am summarizing some of the main issues I had problems with below and how I solved them. Please see the inline documentation in the source code for all the issues and their implementation details.

  1. Creating the ball and animating it: The shape of the rectangular view of the ball as the collision boundary didn’t seem right. Though prior to iOS 9 I don’t think it was possible to do anything about it. Please see Variation on Dropit Demo from Lecture 12 on how I solved this by setting UIDynamicItemCollisionBoundsType to be an .Ellipse.
  2. Animating the paddle on pan gesture and having the ball collide. Hints are given in the assignment specifications on how to implement this, but since I hadn’t done it before it wasn’t clear what the outcome would look like.
    The solution is to add the paddle as a subview of the game view and additionally create a bezier path that acts as a collision boundary in the UIDynamicBehavior subclass. Then update that boundary repeatedly whenever the paddle moves.
    Please see the movePaddle and syncPaddleBoundary methods for details.
  3. When the paddle was moved too quickly when hitting a ball, the ball would often end up trapped inside the paddle. The way I solved this is first check if the new paddle view’s frame intersected with the balls frame using CGRectIntersectsRect. If the frames don’t intersect then update / sync the boundary.
  4. Bricks are setup similar to the paddle, where they are added to the game view and their colliding boundaries added to the UIDynamicBehavior subclass.
    The ball collides with the boundary and when a collision is detected, the brick is removed from the game view. A bricks array [String:Brick] is used to track all the bricks in the game view and match them against the NSCopying identifier from the collision delegate.
    For details please see the methods createBricks and collisionBehavior.
  5. Special bricks and what behavior they would cause were open ended in the assignment specifications. I used 4 kinds of special bricks, one kind requires 3 hits before it disappears and the other three drops special powers that cause:
    • paddles to become larger
    • paddles to become smaller
    • adds additional balls
  6. Pausing the game when user taps on Settings. This wasn’t too hard to implement, the main issue here is the moving ball(s). I used an array to capture the balls and remove them from the screen. When user came back, I re-created them and added back their linear velocity. Please see method settingsDidUpdate.
  7. Instead of putting up an alert when the game ends, a view is used (where it’s state is toggled) to show that the game is over indicating if you won or lost. This view is also used during startup. The startGame and gameOver methods show how this is done.

The following extra credit tasks were also attempted:

  • Use sophisticated Dynamic Animation. For example, you might find a creative way to use the action method in a behavior or use something like linear velocity in your calculations.
  • As mentioned above, creativity will be rewarded, especially interesting game-play settings.
  • Do some cool artistic design in your user-interface (either by drawing or using images).
  • Pausing your game when you navigate away from it (to go to settings) is a bit of a challenge (because you basically have to freeze the ball where it is, but when you come back, you have to get the ball going with the same linear velocity it had). Give it a try. It’s all about controlling the linear velocity of the ball.

Video Demo

Variation on Dropit Demo from Lecture 12: Dynamic Animation, CS193P, Stanford University

Usually it doesn’t make much sense to repeat code from a lecture demo, but for the Dropit project I think it’s worth to post an article based on a slight variation using the new features of UIKit Dynamics available in iOS 9.

This is perhaps a good time to mention that all the CS193P assignment solutions so far created has been based on Swift 2.1 and iOS 9, whereas the Stanford U. lectures and demos are based on Swift 1.2 and iOS 8.

The motivation to create the variation was a result of attempting to implement assignment 5. Particularly the ball which is a UIView and ideally should be round, even though UIViews are obviously rectangles. The good news is that iOS 9 provides a collisionBoundsType property which can be easily overridden in UIView:

class SphereView: UIView {
    // iOS 9 specific
    override var collisionBoundsType: UIDynamicItemCollisionBoundsType {
        return .Ellipse
    }
}

This sets the bounds of the view to be an ellipse and allows the right boundary collisions
as you might expect from a ball or sphere.

dropit-spaces-between-spheres dropit-no-spaces-between-spheres

The UIFieldBehavior new in iOS 9, also seems very interesting with properties like: dragField, springField, electricField, magneticField, noiseFieldWithSmoothness and more, which opens the door to new possibilities of animation in your apps. The Dropit variation also adds the noiseFieldWithSmoothness behavior for some cool
visual effects.

dropit-spheres-in-noise-field

With debugEnabled for UIDynamicAnimator (by adding a Swift bridging header *), you can see the noise field in action as it shifts by adding random noise. To enable UIView debugging, the following code needs to be added in the bridging header file:

@import UIKit;

@interface UIDynamicAnimator (AAPLDebugInterfaceOnly)

// Used in DropitViewController.swift file:
// lazilyCreatedDynamicAnimator.debugEnabled = true
@property (nonatomic, getter=isDebugEnabled) BOOL debugEnabled;
@end

Full source code of the demo is available here at Github:
https://github.com/sanjibahmad/Variation-on-Dropit-Demo

Video Demo

For more on what’s new in UIKit Dynamics in iOS 9, please see the WWDC 2015 video: What’s New in UIKit Dynamics and Visual Effects

* Please see this article on how to add the Swift bridging header: Adding a Swift Bridging Header

A List of Swift and iOS Learning Resources for an Effective Learning Path

I have compiled the following resources based on my own experience and what I believe would be an effective learning path for beginners to get up to speed on iOS development.

1. Udacity

Start with the free iOS courses available at Udacity. They are not only fun and engaging but at the end will help you build 4 resume-worthy demos that you can showcase.

Additionally the following iOS specific free courses from Udacity are also recommended:

Time commitment: X months depending on your commitment

2. Ray Wenderlich

While taking the Udacity course, visit Ray Wenderlich http://www.raywenderlich.com/tutorials from time to time. Pick a topic or article that interests you and go through it.

The idea is, instead of going through everything available from A-Z, you pick something of interest and thoroughly explore it. Each article is on a particular topic and the time-investment is at most a few hours (in contrast to going through an entire book or course).

Time commitment: X hours depending on your commitment

The problem that I have experienced in learning any new technology is information retention. I found the above 2 techniques work well for me because:

  1. One path explores the area comprehensively with loads of relevant industry-specific projects, materials, demos, practice, quizzes, etc.
  2. Another path runs in parallel, diving deep into topics of personal interest for short sprints.

3. Stanford U.

Update, Jun 6, 2016: The latest course from Stanford U. “Developing iOS 9 Apps with Swift” can be found here: https://itunes.apple.com/us/course/developing-ios-9-apps-swift/id1104579961

Once the Udacity courses are done, take the Stanford U. course CS193P available for free on iTunes (https://itunes.apple.com/us/course/developing-ios-8-apps-swift/id961180099) for upping your game-level on iOS development. Some special highlights of the CS193P course that I found interesting were:

Using enums, structures, protocols, property observers, optional chaining, GCD, code re-use, OO design, MVC, autolayouts, iPhone/iPad compatibility, avoiding memory cycles, animations, internationalization, programming insights, well-designed assignments and much more. Using these in practice and specially in correct form as expected from a Stanford U. course, will definitely make you a better developer.

4. Additional Resources

Then further sharpen your axe, polish your skills and stay up-to-date with:

5. Algorithms

Useful for practicing algorithms in Swift for coding-tests/interviews. The sites below allow you to type the code solutions in Swift and run them online for evaluation.

6. Even More Resources

And here are even more resources added on request by the owners of the respective sites.
Enjoy 🙂

Smashtag: Assignment 4, Stanford University, CS193P, Winter 2015

This is the 4th assignment from the course Developing iOS 8 Apps with Swift, Stanford University, CS193p, Winter 2015. There is one more assignment left in this course.

Platform: iOS 9, Swift: 2.1

Full source code available here at Github repository

Smashtag is a Twitter based app that allows users to:

  • perform Twitter search queries
  • view Tweet details (including images, links, users, hashtags)
  • save 100 most recent queries in a Recent tab
  • browse Tweet images in Colllection View

All the 10 Required Tasks were completed. In addition the following Extra Credit items were implemented:

  • In the Users section of your new UITableViewController, list not only users mentioned in the Tweet, but also the user who posted the Tweet in the first place.
  • When you click on a user in the Users section, search not only for Tweets that mention that user, but also for Tweets which were posted by that user.
  • Make the “most recent searches” table be editable (i.e. let the user swipe left to delete the ones they don’t like).
  • Add some UI which displays a new view controller showing a UICollectionView of the first image (or all the images if you want) in all the Tweets that match the search. When a user clicks on an image in this UICollectionView, segue to showing them the Tweet.
  • It would be cool to have “pinching” on the UICollectionView make the cell’s size get larger and smaller (i.e. showing more or fewer images).

Video Demo

GraphingCalculator: Assignment 3, Stanford University, CS193P, Winter 2015

The Graphing Calculator project is a continuation of the previous 2 assignments from the Stanford University CS193P course Developing iOS 8 Apps with Swift, available for free on iTunes. This is the third and final assignment in the Calculator series.

Full source code available here at Github repository

For the other 2 projects, please see:
CalculatorBrain: Assignment 2, Stanford University Winter 2015 (iOS)
Calculator: Assignment 1, Stanford University Winter 2015 (iOS)

Graphing-Calculator_cs193p_Stanford-University

This project provides graphing features in addition to the regular calculator functions. Graphs can be plotted by entering expressions where M is the independent variable. Please see examples below.

To plot M, enter:

M, Graph

To plot sin(M), enter:

M, Sin, Graph

To plot M x cos(M), enter:

M, M, cos, x, Graph

Some interesting notes

  • The CalculatorBrain is reused to calculate the values of M for graphing
  • Plot values are set in the GraphingViewController as the data source of GraphingView
  • To fix the sluggish performance when zoomed out and panned, only the number of plots required for the screen width are calculated
  • Graph scale and origin is stored in NSUserDefaults
  • Upon device rotation, the graph is centered and adjusted slightly with the width and height change ratio

Video demo

Some Interesting Swift Tidbits

Some interesting Swift tidbits with practical code examples. Implications: use them in your projects for more readable and maintainable code.

Declaring multiple values in a single line
Multiple variables or constants can be declared in a single line using commas to separate them:

var red = 141.0, green = 185.0, blue = 230.0, alpha = 1.0

 
They can also be declared in a single line by adding the type annotation to the final variable:

var red, green, blue, alpha: Double

 
Large number readability
For large numbers, we can use underscore for better readability:

let mapRadius = 100_000

 
Using typealias for readable code
Using typealias for more readable code. For example, var program contains AnyObject, the primary purpose of creating var program is to use it as a property list. So instead of declaring:

var program: AnyObject?

 
We can typealias PropertyList = AnyObject, and use PropertyList for the var program type.

typealias PropertyList = AnyObject
var program: PropertyList?

 
Defining optional variables with nil value
When defining an unknown optional variable it doesn’t need to be explicitly set to nil. Swift automatically sets the variable to nil. For example:

var error: String? = nil // Not needed
var error: String?       // Swift automatically sets it to nil

 
Multiple optional bindings for concise and legible code
Multiple optional bindings help avoid many layers of hard to read nested code. For example,

The pyramid of nested optional bindings (hard to read):

if let firstNumber = Int("123") {
    if let secondNumber = Int("456") {
        if firstNumber < secondNumber {
            print("\(firstNumber) < \(secondNumber)")
        }
    }
}
// prints "123 < 456"

 
Multiple optional bindings (elegant):

if let firstNumber = Int("123"), secondNumber = Int("456") where firstNumber < secondNumber {
    print("\(firstNumber) < \(secondNumber)")
}
// prints "123 < 456"

 
Nil coalescing operator
Helps provide a default value if the evaluation is nil. For example,

tipPercentageForRestaurant is nil, so tipPercentage is 0.0:

var tipPercentageForRestaurant: Double?
let tipPercentage = tipPercentageForRestaurant ?? 0
print(tipPercentage)
// prints 0.0

tipPercentageForRestaurant is 0.15, so tipPercentage is 0.15

var tipPercentageForRestaurant: Double?
tipPercentageForRestaurant = 0.15
let tipPercentage = tipPercentageForRestaurant ?? 0
print(tipPercentage)
// prints 0.15