Feeds:
Posts
Comments

Posts Tagged ‘Swift’

I’m big on education, think Swift is a great language, and believe games can be a practical way to motivate learning. So, how did I put this into practice?

What’s My Motivation?

During my career, I’ve had the opportunity to teach programming and software development (two distinctly different things) to both teens and adults. One thing that’s always struck me is the disjoint nature of the material. Not in terms of the subject matter, but rather with respect to the examples being used. I learning a spoken language, you don’t abandon a part of speech as you acquire another. Learning is both cumulative. As we learn, we revise our approach.

In teaching programming, we seem to be so focused on being focused, that we divorce ourselves from the actual processes that go on when we solve real-world problems. In the past few years, I’ve noticed that people are producing programming language courses reduced to five minute info-bites. Here’s the thing, software development is a long-form practice.

Early Insight

I put together my first programming curriculum in 1981 when I was a instructor at Computer Camp, Inc. in Santa Barbara, California. The students were teens and the problem in my mind was motivation. Unlike adults, most of the teens I’ve taught over the years don’t approach programming from experience. They have a beginners mind. This is both good and bad for a teacher. The good is that they don’t have bad habits yet. If properly taught, they will think in the language. The bad is that we, as experienced developers, have come to see programming languages as a collection of “computer language components” and not as a methodology for solving problems as expressed in a specific syntax. As a result, the vast majority of software written today would have the spoken equivalent of transliteration. All the words are there and a native speaker could probably make sense of it, but they would suffer greatly.

In 1982, I found myself tasked with teaching an advanced BASIC programming class. It was then that I hit upon the idea of a dungeon crawler. The students were interested from the outset. They appreciated that everything they were spending their precious time on was leading to the outcome. They looked at the language as a means to solve a problems and not a way to take a solution from another language and reapply it.

So, now I understood that it was possible to motivate and teach people how to think in a programming language. Could I leverage this understanding?

Teaching Revisited

In 2008 I had the opportunity to teach electrical engineers C++ and SystemC. These were individuals who’s software development experience was grounded in C programming. Their code and indeed, approach to software development, was procedural as once might expect. In order to teach them SystemC, people must first learn C++ (the language SystemC is written in). After working with the materials we had been using, I felt strongly that we weren’t motivating an appreciation and understanding of object orientation. I had the opportunity to participate in the creation of an entirely new C++ curriculum. From the beginning it introduced object orientation. There is a interesting shift that takes place when the responsibility for the data shifts from all the code that touches it to objects that manage it.

The Stanford Way

I’ve been watching Stanford’s iOS development course (CS193P) since it was first made available. It has undergone an interesting evolution over the past decade. Initially, it taught Objective-C development and iOS programming. This included pure (non-GUI) Objective-C and test driven development. With the fundamentals in place, the model-view-controller paradigm was taught as the foundation of iOS development. Then the class shifted into the standard piece-part methodology we see everywhere, albeit with a distinctly iOS bent.

Over the years, both the pure language and test driven development aspects went away. These were relegated to reading material. Objective-C was supplanted by Swift. More sophisticated areas were covered as the iPhone evolved. By the end of the course, students can build complex apps. But it feels like people are learning APIs rather than the language. But what can you do in 10 weeks? Would people actually pay for a college course to learn Swift and then another for iOS development?

Enter Wumpus

About five years ago, someone asked me to teach them how to make iPhone games. They had no software development experience and little desire for the traditional approach of learning via classes or books. They understood the ins and outs of game play and had a keen sense of what made a game playable.

The process that followed was the condensation of forty years of writing code and developing software. Today, when we work with just about any OS API, we have to deal with a context. But how do you motivate the very idea of the context. How do you teach people to work effectively with the net result of over fifty years of software development practices without just expecting that people will simply accept that this is the way it is and you just have to accept it? You can easily create an animation, but what is happening behind the scenes? Being able to understand and explore these questions is what will determine if someone will be capable of working beyond the software equivalent of writing pulp fiction.

In the end, I settled on teaching software development through the very old game of Hunt the Wumpus. This game appeared in the original Unix distributions. It has simple rules, a bit of action, some random elements and is, on the whole, able to be understood by a nine-year-old. It’s implementation can be used to demonstrate multi-dimensional arrays, randomization, object-orientation, internationalization, error handling, data visualization and testing.

As this was before Swift, it was implemented in Objective-C.

Personally, I used my implementation of Wumpus to experiment with iOS. Specifically, I was tinkering with storyboards in Xcode. I wanted to see if it was possible to implement the user interface of Wumpus entirely using scenes representing the rooms within the game. This is, of course, a horrific abuse of the scene concept and is the equivalent of unfolding an array of objects into individual routines. It did, in fact, work. And I would not ever recommend that the technique be used for production code.

Enter Swift

Two years ago Apple announces Swift. Immediately, I started working with it. Like many languages before it, Swift incorporated lessons learned. In the case of Swift, many lessons were learned. You can look at my earlier posts to see my past musings on the language.

In May, I found myself with sufficient time on my hands to undertake a rewrite of Wumpus in the soon to be released (now just released) Swift 3. Concurrently, iOS 10 was to come out and would be supported by Xcode 8. Changes all around. My initial Wumpus model was readily brought over from Objective-C. Over time I realized that many of the things in that implementation could be completely folded down to a single line of Swift code. Swift wasn’t an extension of an older language. In fact, as the language evolved from version 1 to 3, many elements initial present were removed or replaced. Today’s Swift is much more consistent as a result.

I knew the pieces of the user interface that would be required and set about recreating them. This time is a sane fashion. Once this was done, I began the process of connecting the view to the controller layer and eventually the model. All the while, adopting the Swift 3 and iOS 10 idioms.

At this point, I had a playable version of Wumpus. There was a main scene that took you to the rules or the game. The rules were a static chunk of text. The credits was static attributed text. You could navigate the maze and be moved (scene with alert) or die (scene with alert). Shooting came in and initially used a scrolling picker with the room numbers. Dull stuff.

Just Add … Everything

Now came the interesting bits. The iOS-specific bits.

It’d be dull to cover this in detail, so here’s a rough sequence.

  • 30+ background images
  • danger annunciator images
  • tint overlay to gray scale backgrounds
  • ambient sound across scenes (looped soundtrack)
  • incidental sounds within scenes (looped for danger and one-shot for events [moved, died])
  • added settings controls for all audio volumes
  • asset catalog used for both image and sound management (simplified access)
  • rebuilt settings using a table with dynamically constructed cells with action handlers
  • saved statistics using class-based archiver
  • rebuilt statistics using dynamic data generation from the statistics data
  • segues and segue unwinding (navigation control)
  • timers (scene auto-transition from title scene)
  • tap gestures (eliminating navigation buttons)
  • replaced static rules text with chunked pages and swipe gestures
  • custom font (Kalam)
  • parallax (titles, danger annunciators and event imagery)
  • dynamically constructed attributed text (credits)
  • endless scrolling text loop (credits)
  • dynamically constructed tables from plist data (statistics field names)
  • static collection view replacing lame picker interface (shoot scene)
  • app analytics (Firebase)
  • ad support (AdMob)
  • JSON processing (credits source import)
  • core data (credits attributed string construction)
  • built to work with both iOS 9.3 and 10.0 (core data had a major change)
  • social network (Facebook / Twitter) posting

Testing, Testing

An important part of creating an iPhone application is being able to ship it. But before that you should really test it. A lot. Really.

To do that you need to do the dance of getting certificates and creating an app instance. With these you can push builds to Apple’s servers where they can be accessed by internal testers (all builds) and external testers (specific builds, after review [sort of]). Then comes the great fun of prodding the testers.

Collateral Damage

It’s been tested. All the features (for this release) are present. And it’s time to ship, right? Actually, no. You can’t ship an app without creating a bucket and a half  of collateral images (screenshots) for the app store. There’s also the small matter of the web site that will support the app. And no self-respecting app would go up without a game play video.

About those images. You technically only need one set at the highest screen geometry. The others will be generated by scaling. Now, you’ve gone to all the trouble of adopting an adaptive user interface so things look reasonable on all the various screen geometries, so not generating imagery for every size would just be lazy. Happily, all these can be generated from simulator screen capture. Image having to round up half a dozen devices just to do screen caps. Did I mention that video? Well, you can’t video capture from the simulator. So, for those of you who look at my app on the store, there’s just the one from my current iPhone.

I do keep referring to Wumpus as an iPhone app. Well, it is. I designed it for portrait-only. Now this doesn’t prevent you from putting it on an iPad. The problem is that Apple has never updated the screen size used from iPhone apps on an iPad. It’s this pointlessly scrunched up screen size. It looked brain dead. So, I went back and tweaked the layout to be less egregious. It’s not pretty, but why are you running it on an iPad in the first place?

Can I go now?

What could possible be left to do?

  • specification of age rating
  • description for the store
  • verification that you own or have license for all the bits you’re using
  • text for alerts presented to the user, if certain features are used

About that whole licensing point. Wumpus uses a lot of images and audio tracks. They all need to be acknowledged properly. That was a driving factor in using Core Data to track them. All the ones I used were either public domain or minimally encumbered. The biggest problem I had was not finding them, but selecting from among them.

And yes, now it’s ready to ship.

Ship It

So, about two weeks ago, submitted Wumpus for review. Well, I tried to. Apple will only review apps built against finalized OS libraries. Wait. Wait. So I added a few more bits to fill the time. On Monday 12 September 2016, I was able to submit Wumpus for review. After a brief diversion of trying to find out how to answer new privacy questions related to the use of Firebase and AdMob. Then came the wait. Did I forget something? Was there some horrible error condition lurking waiting for the mystical Apple auto application checkers to detect. Would the review be delayed by more relevant applications (honestly, that’s just about every other app)? Nah, it was all good.

On Wednesday 14 September 2016, I got an auto-generated email informing me that my app was available for sale. Pretty anti-climactic really. If you have an iPhone/iPad, you can download it today. The related web site is also online.

And?

So where’s the tie-back to the teaching programming / software engineering? That was the point, right? Absolutely. I’m not done. Although Wumpus represents an interesting résumé piece and I’ll be extending it with additional technologies (such as web, Apple Watch), my take away is an example that I know I can use to teach both Swift and iPhone development. Like all good stories, this one leaves me wanting more.

Read Full Post »

iOS 10 ships on September 13th. Apple has changed their generated code for Core Data. It doesn’t compile if you set your deployment target to iOS 9.3. What’s a developer to do?

For a very long time now, Apple has be proud, and deservedly so, that their users are overwhelmingly keeping up-to-date with the latest releases of their operating systems. As such, Apple’s messaging to developers is to support the current and previous OS version. Most of the time, this isn’t a big deal. Sometimes, it is. With the latest changes related to Core Data, it’s a problem.

If you create a new Xcode project that will being using Core Data, you get some useful code bits in the AppDelegate. In Xcode 8, you get the following (comments removed for brevity):

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "coreme")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()
 func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

This works great if you’re only going to build for iOS 10, but if you try to set your deployment target to iOS 9.3 as recommended, you’ll get the following error:

AppDelegate.swift:49:35: 'NSPersistentContainer' is only available on iOS 10.0 or newer

Well, that’s not good.

As users of Core Data know, operations using it use a database context. You can see it being used in the saveContext function above. Here we see that the context is a member of the persistentContainer. Since this doesn’t exist in iOS 9.3, we’ll have to get it some other way.

Let’s look at what used to be supplied with Xcode 7 (udpated to Swift 3):

lazy var applicationDocumentsDirectory: URL = {
    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return urls[urls.count-1]
}()

lazy var managedObjectModel: NSManagedObjectModel = {
    let modelURL = Bundle.main.url(forResource: "bfoo", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator =
{
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
    
    do {
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
    } catch {
        let dict : [String : Any] = [NSLocalizedDescriptionKey        : "Failed to initialize the application's saved data" as NSString,
                                     NSLocalizedFailureReasonErrorKey : "There was an error creating or loading the application's saved data." as NSString,
                                     NSUnderlyingErrorKey             : error as NSError]
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        print("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }
    
    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

I’ve left out the saveContext function as it’s only distinction is where it gets the context from. Above, we see that the context is a separate variable.

Now without a doubt, the iOS 10 code is much simpler, but, if we want to be able to do the right thing and support both current and last version, we need a bit of a mash up. It’s a bit tedious, but you only have to build it once (hint, hint Apple). Here’s what I’ve come up with.

// MARK: - utility routines
lazy var applicationDocumentsDirectory: URL = {
    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return urls[urls.count-1]
}()

// MARK: - Core Data stack (generic)
lazy var managedObjectModel: NSManagedObjectModel = {
        let modelURL = Bundle.main.url(forResource: modelName, withExtension: modelExtension)!
        return NSManagedObjectModel(contentsOf: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let url = self.applicationDocumentsDirectory.appendingPathComponent(modelName).appendingPathExtension(sqliteExtension)

    do {
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
    } catch {
        let dict : [String : Any] = [NSLocalizedDescriptionKey        : "Failed to initialize the application's saved data" as NSString,
                                     NSLocalizedFailureReasonErrorKey : "There was an error creating or loading the application's saved data." as NSString,
                                     NSUnderlyingErrorKey             : error as NSError]
        
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        fatalError("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
    }
    
    return coordinator
}()

// MARK: - Core Data stack (iOS 9)
@available(iOS 9.0, *)
lazy var managedObjectContext: NSManagedObjectContext = {
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)    
    managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator    
    return managedObjectContext
}()

// MARK: - Core Data stack (iOS 10)
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: creditsModelName)    
    container.loadPersistentStores(completionHandler: {
        (storeDescription, error) in
            if let error = error as NSError?
            {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        }
    )
    
    return container
}()

// MARK: - Core Data context
lazy var databaseContext : NSManagedObjectContext = {
    if #available(iOS 10.0, *) {
        return self.persistentContainer.viewContext
    } else {
        return self.managedObjectContext
    }
}()

// MARK: - Core Data save
func saveContext () {
    do {
        if databaseContext.hasChanges {
            try databaseContext.save()
        }
    } catch {
        let nserror = error as NSError
        
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }
}

I’ve introduced databaseContext as the context variable to be used throughout. I think it’s more clear and now saveContext doesn’t have to care which OS you’re targeting. With this change in place, you can now safely target 9.3 and still build for 10.0.

Read Full Post »

One of the challenges in learning a new language, be it human or computer, is learning to think in the language. Learning Swift is no different.

I’ve been spending the past several months working on the first iOS (iPhone) app that I’ll be releasing through the Apple app store. I’m writing it entirely in Swift 3, the latest version of the language. Yesterday, I was looking over the code to see if there were any places where I’d been thinking in a non-Swift fashion. This moment of reflection was triggered by my viewing of a very recently released class in Swift from one of the major online education sites. I was disappointed that the instructor was using an idiom that I knew was easily simplified in Swift. My disappointment made me wonder if I had similar issues.

The following is actual code from my upcoming app. I had originally created it’s core in C as an extensible example for teaching that language. The setup is as follows:

  • the map is an array of connections from each room
  • the number of connections from each room is fixed
  • we are explicitly tracking the number of a given type of hazard

We want a function that returns true if there is hazard in one of the connecting rooms. Here’s the original code:

var hazardNear = false
        
if hazardCount > 0
{
    for nextRoom in 0 ..< numberOfConnections
    {
        if hazardRooms.contains(exits[room][nextRoom])
        {
            hazardNear = true
                    
            break
        }
    }
}
        
return hazardNear

Pretty conventional C-esque stuff. The first thing that jumped out at me was the reliance on knowing the number of connections. Swift arrays are true collections. Let’s treat them as such.

var hazardNear = false
        
if hazardCount > 0
{
    for nextRoom in exits[room]
    {
        if hazardRooms.contains(nextRoom)
        {
            hazardNear = true
                    
            break
        }
    }
}
        
return hazardNear

When viewed this way, it’s obvious that we’re just filtering the collection based on a condition. So, just do that.

var hazardNear = false
        
if hazardCount > 0
{
    hazardNear = exits[room].filter{hazardRooms.contains($0)}.count != 0
}
        
return hazardNear

We’re filtering the array of rooms for ones that contain the hazard and checking for a non-zero count. But this is still a bit clunky. Let’s examine what we’re really asking.

var hazardNear = false
        
if hazardCount > 0
{
    hazardNear = !exits[room].filter{hazardRooms.contains($0)}.isEmpty
}
        
return hazardNear

It’s far more clear to simply ask if the filtered array is non-empty directly. What’s left is one final simplification.

return hazardCount > 0 && !exits[room].filter{hazardRooms.contains($0)}.isEmpty

One might ask whether having an explicit count is necessary as the hazard array has a count. True. Although the hazard array is built based on the number of hazards, so I still need it to be around.

Overall, I fairly pleased with the results of the exercise. In the end, the code is much clearer in intent.

Read Full Post »

HackerRank has become a popular showcase for software developers. Its many participants have the ability to choose their language. Recently Apple’s Swift language has been added.

This is all well and wonderful, but as I written about in previous posts, non-UI oriented use of Swift has not been a priority. It’s not impossible, but you have to scrounge for the bits you need to use it.

As those who have used HackerRank know, non-UI is the way of things. So, here are a few bits that make it possible to use Swift in the HackerRank.

Note: In production code, one should always check when unwrapping variables. In HackerRank, input will be well-behaved and the focus is on the internal workings rather than the input mechanism.

Reading a string from the input stream

let string_value = readLine(stripNewline: true)!

Reading a single number from the input stream

let numeric_value = Int(readLine(stripNewline: true)!)!

Reading a string array from the input stream

let stringArray = input.characters
                       .split {$0 == " "}
                       .map (String.init)

Reading a numeric array from the input stream

let numbericArray = input.characters
                         .split {$0 == " "}
                         .map (String.init)
                         .map {(var s) -> Int in return Int(s)!}

Reading mixed values from the input stream

let stringArray = input.characters
                       .split {$0 == " "}
                       .map (String.init)

let iValue1 = Int(stringArray[0])!
let sValue  = stringArray[1]
let iValue2 = Int(stringArray[2])!

Writing single values to the output stream

print(foo)

Writing values in string to the output stream

print ("There are \(found) or \(expected) things")

Writing array values to the output stream

print (array.map { String($0) }.joinWithSeparator(" "))

Why not use extensions, you may ask. You can do that if you like. I thought it would be better here to show the minimal elements. And generally HackerRank in very limited in its input and output aspects.

This should cover all the usual cases for input and output to enable you to use Swift with HackerRank. So, the next time you’re using HackerRank and you don’t see Swift as an option, be sure to ask the author to add it.

Read Full Post »

This is my third post on the Swift command line. In the first, I wrote on how to do command line input with Swift. In the second, I cleaned up the code after a year of tinkering with Swift. In this third installment, I get rid of more Objective-C.

Almost a month ago, Apple released Swift into the open source community. Pretty spiffy that. So, being the language wonk that I am, I bopped over to the Swift site and downloaded the sources. After a bit of scrounging, I discovered that there existed a standard library call to read a line from the input stream. I was a bit disappointed that I’d not seen this talked about anywhere, but that’s life.

So, I’ve updated my code sample and present it below. I do some forced unwrapping as the point is to highlight the process. Be sure to code defensively.

I’ll probably come back to this one more time once I’ve had a chance to look more into the Swift standard library so I can eliminate my untidy Objective-C dependent putString() routine.

//
//  swift_intput_routines.swift
//
//  Created by Charles Wilson on 9/27/2014.
//  Revised by Charles Wilson on 9/27/2015.
//  Revised by Charles Wilson on 12/21/2015.
//
//  Copyright (c) 2014 – 2015 Charles Wilson. All rights reserved.
//
//  Permission is granted to use and modify so long as attribution is made.
//

import Foundation

func putString (outputString : String = “”)
{
if !outputString.isEmpty
{
NSFileHandle.fileHandleWithStandardOutput().writeData((outputString as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
}

func getString (prompt : String = “”) -> String?
{
if !prompt.isEmpty
{
putString(prompt)
}

return readLine(stripNewline: true)
}

func getCharacter () -> Character
{
let inputValue     : UInt32      = UInt32(getchar())
var inputCharacter : Character

inputCharacter = Character(UnicodeScalar(inputValue))

return inputCharacter
}

func getInteger (prompt : String = “”) -> Int
{
if !prompt.isEmpty
{
putString(prompt)
}

return (getString()! as NSString).integerValue
}

func getFloat (prompt : String = “”) -> Float
{
if !prompt.isEmpty
{
putString(prompt)
}

return (getString()! as NSString).floatValue
}

Here’s the main to exercise it.

//
//  main.swift
//
//  Created by Charles Wilson on 9/27/2014.
//  Revised by Charles Wilson on 9/27/2015.
//  Revised by Charles Wilson on 12/21/2015.
//
//  Copyright (c) 2014 - 2015 Charles Wilson. All rights reserved.
//
//  Permission is granted to use and modify so long as attribution is made.
//

import Foundation

var name = getString("What is your name? ")!

if name.isEmpty
{
    name = "George"
    
    putString("That's not much of a name. I'll call you '\(name)'\n")
}
else
{
    putString("Your name is '\(name)'\n")
}

let age = getInteger("How old are you \(name)? ")

putString("You are \(age) years old\n")

// get a value without a prompt
let number = getInteger()

putString("\(number) is a nice number\n")

let floating = getFloat("Enter a floating point number: ")

putString("\(floating) works for me\n")

var c : Character

putString("Type stuff. Enter ^ when done.\n")

let sentinel : Character = Character(UnicodeScalar("^"))
var in_c     : Character

repeat
{
    in_c = getCharacter()
}
while ( in_c != sentinel )

putString("\n\n")
putString("bye\n")

Read Full Post »

Update: Apple released the Swift source. My update based on what I learned is here.

A bit over a year ago, I wrote a post about how I wanted to do command line input in Apple’s then new Swift language.

The post was pretty well received and still get a hit / week.

On the heals of finishing the WWDC 2015 session videos, I decided to start tinkering a bit more with the language. Toward this end, I’ve been re-implementing old command line games from the 1970s that were written in BASIC. This forced me to actually go back to my command line input code. Dutifully allowing XCode to update it to Swift 2 syntax, I noticed that it relied way too much on Objective C bits. I also didn’t like the way it was handling the translation from string to numeric. So, I’ve updated it.

Yes, I should just put it up on GitHub. Maybe later. For now, just cut and paste it.

//
//  swift_intput_routines.swift
//
//  Created by Charles Wilson on 9/27/2014.
//  Revised by Charles Wilson on 9/26/2015.
//
//  Copyright (c) 2014 - 2015 Charles Wilson. All rights reserved.
//
//  Permission is granted to use and modify so long as attribution is made.
//

import Foundation

func putString (outputString : String = "")
{
    if !outputString.isEmpty
    {
        NSFileHandle.fileHandleWithStandardOutput().writeData((outputString as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
    }
}

func getString (prompt : String = "") -> String
{
    if !prompt.isEmpty
    {
        putString(prompt)
    }
    
    var inputString : NSString = ""
    let data        : NSData?  = NSFileHandle.fileHandleWithStandardInput().availableData
    
    if ( data != nil )
    {
        inputString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
        inputString = inputString.substringToIndex(inputString.length - 1)
    }
    
    return String(inputString)
}

func getCharacter () -> Character
{
    let inputValue     : UInt32      = UInt32(getchar())
    var inputCharacter : Character
    
    inputCharacter = Character(UnicodeScalar(inputValue))
    
    return inputCharacter
}

func getInteger (prompt : String = "") -> Int
{
    if !prompt.isEmpty
    {
        putString(prompt)
    }
    
    return (getString() as NSString).integerValue
}

func getFloat (prompt : String = "") -> Float
{
    if !prompt.isEmpty
    {
        putString(prompt)
    }
    
    return (getString() as NSString).floatValue
}

I also update the test routine as I wasn’t checking the float bits.

//
//  main.swift
//
//  Created by Charles Wilson on 9/27/2014.
//  Revised by Charles Wilson on 9/26/2015.
//
//  Copyright (c) 2014 - 2015 Charles Wilson. All rights reserved.
//
//  Permission is granted to use and modify so long as attribution is made.
//

import Foundation

var name = getString("What is your name? ")

if name.isEmpty
{
    name = "George"
    
    putString("That's not much of a name. I'll call you '\(name)'\n")
}
else
{
    putString("Your name is '\(name)'\n")
}

let age = getInteger("How old are you \(name)? ")

putString("You are \(age) years old\n")

let number = getInteger()

putString("\(number) is a nice number\n")

let floating = getFloat("Enter a floating point number: ")

putString("\(floating) works for me\n")

var c : Character

putString("Type stuff. Enter ^ when done.\n")

let sentinel : Character = Character(UnicodeScalar("^"))
var in_c     : Character

repeat
{
    in_c = getCharacter()
}
while ( in_c != sentinel )

putString("\n\n")
putString("bye\n")

Read Full Post »

It took me a bit longer than I’d’ve liked, but finishing all the Apple WWDC 2015 videos (110-ish) in under three months is pretty satisfying.

I’m impressed at the speed with which Apple is executing the change of primary development language from Objective-C to Swift. I expected three years, but it looks like they’ll have things wrapped up in two. This is no mean feat. I’ve now experienced three core language shifts within Apple now. The first was from the Apple ][ 6502 assembly to the Macintosh 68000 assembly / Pascal hybrid. The second was the move to C. This was particularly tedious for those of us attempting to keep both camps happy. You haven’t lived until you’ve dealt with byte-prefixed, null-terminated strings. With the adoption of NextStep and the BSD/Mach micro-kernel can the transition to Objective-C. I’ll admit, I made fun of Objectionable-C. By that time, I’d spent the better part of a decade using C++. A bit of snobbery on my part. Those two children of C have fundamentally different views of the world. I cut my teeth on iOS using Objective-C and appreciated its extensibility when compared with C++. But, it didn’t have the base that C++ did. A billion devices later, well, that’s a different story. Now we have Swift. I believe that it represents the next generation of language. Not object-oriented or message-oriented, but protocol-oriented.

The number of sessions dedicated to tools was impressive as always. As was the quality of the presentations. Thankfully, we were spared the pain of having Apple’s french speakers presenting in English discussing graphics which the word banana coming up so often that one would think there was a drinking game just for that session.

I’m looking forward to tinkering with the WatchOS bits. Those sessions are probably a staple of developers.

Props goes out to the Xcode developers of continuing to bring a quality product to the table. An AirPlay view for the simulators would be nice (hint, hint). The sessions dedicated to the profiling, power and optimization of code are worth watching multiple times.

As is the case with many mature elements of the operating systems, security had fewer explicit sessions. Instead, security was a pervasive theme along with privacy.

One cannot talk about this years sessions without mentioning the brilliant leveraging the synthesis of scale and privacy to created ResearchKit.

The care that Apple puts into the sample code is truly inspiring. Having suffered through hundreds of pages of AOCE documentation, today’s entry into Apple development seems easy. Easy on the individual component level at least. There is not more that one would have to learn in order to create software from beginning to end with the level of quality and feature richness that the world has come to expect from applications on the Apple platforms.

Leaving the best to last, I’ll reflect on an issue that’s always bothered me with the transition strategy that Apple has used in the past. It’s not so much that I didn’t like the solution they came up with to deal with transitioning from one methodology to another. Or that I had a better answer, I didn’t. The price always seemed rather steep to me. I speak of binaries with multiple code and data resources used to allow a user to download a single image and run it anywhere. This was used in the transition from 68000-based machines to PowerPC ones and again when moving to Intel’s architecture. On iOS, we’ve seen the number of duplicate resources steadily climb as the screen geometries and densities have increased. The thing of which I speak is the double-headed axe of app thinning and on-demand resources. The ability to release an application to the store with all the bits for all the supported devices and be able to download only those that will actually be usable on a given device is tremendous. Couple that the a way to partition an application in such a way that only the resources within a user’s window of activity are present on the device and you have a substantial savings in both time and memory. Well done.

It’s been many years now since I’ve been able to attend WWDC in person and given the popularity of the conference, it’s not likely that I’ll be going any time soon. I’m content for the moment to be able to access all the content, if not the people, that someone attending would be able to. I look forward to next year’s sessions.

Read Full Post »

It’s been five months since Apple’s Worldwide Developer Conference ended. This year the WWDC iOS application had the session videos available sooner than ever. I’d been watching them during my commute to and from Portland’s downtown. Well, this past week, I finished watching the last one. And with 107 videos, it’s Apple’s version of Netflix putting up a few years of Doctor Who episodes for people to gorge on.

Truth be told, I would have finished a month ago. So, what was the hold up? iOS 8 released. In doing so, it revealed that some change in the OS caused the WWDC app to crash when you tried to view a video. Very sad. The really unfortunate part is that I was only four videos away from having watched them all.

Well, I’m happy to report that the WWDC app is now working fine and I’d encourage anyone who’s doing OSX or iOS development to take advantage of them. There is a tremendous amount of information on the latest tools, technologies and techniques. Swift and Metal feature prominently.

Now, I’m not saying that these are all Jobsian quality presentations. As much as I appreciate that software development is a global endeavor, whoever decided that someone with a pronounced French accent should be littering his presentation with the word banana should be forced to watch that session from beginning to end. Subtitles would also have helped some sessions.

All-in-all these presentations are well crafted and delivered. Apple also continues its tradition of providing substantive sample code. Nothing is worse than code snippets that don’t convey the true flavor of using an API as you would in practice. Happily gone are the days when the AOCE (Apple Open Collaboration Environment) documentation was 1200 pages of paper with no index. Not the best way to pick up a new technology.

So if you need a break from watching the original run of The Tomorrow People, the WWDC sessions are there for you.

Read Full Post »

Update 2015-12-21: Apple released Swift source code. I’ve updated my sample again to reflect what I learned.

Update 2015-09-27: It’s been a year and much has happened with Swift. Please see my latest post on Swift command line input for current code.


Recently I’ve been watching Stanford intro CS classes. I like to see how they present the fundamental concepts and techniques of programming. This got me thinking about those missing bits of Swift that would allow me to actually write a command line-based application. [see my previous post Swift: Second Things First] Having these bits would be to allow me to teach Swift as a first language without having to teach the abstractions and interfaces required to properly develop for a graphical interface. I’m not much into attempting to teach in a way that breaks the “go from strength to strength” methodology. If you’re going to teach me to sing, it’s a whole lot easier if I don’t have to learn how to spin plates at the same time.

So, I spent some time and created a simple set of routines that when added to a Swift command line application allow you to get and put strings, integers and floats. Not exactly rocket science, which begs the question, “Why didn’t Apple do it?” Well, since I’m not Apple, I have no idea.

Here without further comment is the content of the file I wrote. That it is not the best Swift code, I have no doubt. If you can make it better, cool. And Apple, it you read this, please make something sensible of it.

Update: I’ve manually wrapped a few lines as WordPress is clipping.

//
//  swift_intput_routines.swift
//  swift input test
//
//  Created by Charles Wilson on 9/27/14.
//  Copyright (c) 2014 Charles Wilson.
// Permission is granted to use and modify so long as attribution is made.
//

import Foundation

func putString (_ outputString : NSString = "")
{
  if outputString.length >= 1
  {
    NSFileHandle.fileHandleWithStandardOutput().writeData(
               outputString.dataUsingEncoding(NSUTF8StringEncoding)!)
  }
}

func getString (_ prompt : NSString = "") -> NSString
{
  if prompt.length >= 1
  {
    putString(prompt)
  }

  var inputString : NSString = ""
  let data        : NSData?  = NSFileHandle.fileHandleWithStandardInput().availableData

  if ( data != nil )
  {
    inputString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
    inputString = inputString.substringToIndex(inputString.length - 1)
  }

  return inputString
}

func getInteger (_ prompt : NSString = "") -> Int
{
  if prompt.length >= 1
  {
    putString(prompt)
  }

  var inputValue : Int = 0
  let inputString = getString()

  inputValue = inputString.integerValue

  return inputValue
}

func getFloat (_ prompt : NSString = "") -> Float
{
  if prompt.length >= 1
  {
    putString(prompt)
  }

  var inputValue : Float = 0.0
  let inputString = getString()

  inputValue = inputString.floatValue

  return inputValue
}

And here’s a little test program that uses it.


//
//  main.swift
//  swift input test
//
//  Created by Charles Wilson on 9/27/14.
//  Copyright (c) 2014 Charles Wilson. All rights reserved.
//

import Foundation

var name = getString("What is your name? ")

if name.length == 0
{
  name = "George"

  putString("That's not much of a name. I'll call you '\(name)'\n")
}
else
{
  putString("Your name is '\(name)'\n")
}

let age = getInteger("How old are you \(name)? ")

putString("You are \(age) years old\n")

let number = getFloat("Enter a number with a decimal point in it: ")

putString("\(number) is a nice number")

putString("\n\n")
putString("bye\n")

You’re probably wondering why I don’t use print(). Well, print() doesn’t flush stdout’s buffer. And, I really like to enter data on the same line as the prompt. And for those of you who say that you can use print() in XCode’s output window, I’ll remind you that a simulator isn’t the target device.

“But, wait. You didn’t comment the code.” No, I didn’t. By the time a student has enough understanding of Cocoa to compose the I/O routines provided above, the comments would be unnecessary.

So, there you have it. The typical second program that you’d ask a student to write.

Read Full Post »

I’ve been looking at Swift for about a month now. My first thought when I see a new language is,

How would I teach this language to someone new to programming?

After spending countless hours dealing with the little things in a language that contribute to the lack of patience developers have with non-developers, I still hold out hope that we will have learned from our past and can create a language which will enable those of us who toil in darkness to get out a bit more.

Back in the day, when a new language emerged from the primordial soup, it was accompanied by a language description. This document is ensures that in the case where the creator(s) of the language are run down by a rampaging gaggle of salvage yard geese mysteriously loosed by the supporters of the favorite language de jour will still be available to the six people already using it. [Just like Apple’s linker that was written in Oberon. But that’s a story for another day.] Lest you are under the mistaken impression that this document is the be-all and end-all of the language, I would refer the gentle reader to the first Ada spec which indicated that a unary minus could be present in the middle of a digit string.

Sometime later, a language manual would appear. If you are very lucky, this will be written by a teacher (Pascal User Manual and Report). Alternately, it may be written by a practitioner who is known for their ability to create concise code like awk (The C Programming Language). If you’re really lucky, the author may be both a teacher and practitioner who’s book printings required the deforestation of small pacific islands (The C++ Programming Language). Regardless of the provenance, only those who live on the bleeding edge or college (more recently high school) students embrace these tomes of wonderment.

Assuming that the language becomes popular enough to catch the attention of people other than the full-stack crowd, a book may appear whose clarity will ensure that it is longer lived than the inevitable dummies book. This rare collection includes the A FORTRAN Coloring Book, Basic BASIC, and Programming in C.

So far, Apple has released three documents on Swift. The first was the language reference. The second details Swift-ObjectiveC interoperability. The latest is the Swift standard library reference.

This year’s WWDC included seven Swift-specific sessions and eight others that referred to it. This level of coverage is quite impressive, but then again, they’ve been working on the language for about four years.

Enough background already, how would I teach Swift as a first programming language?

Unfortunately, right now, today, I can’t. You can tinker with Swift in playgrounds. You can integrate Swift and ObjectiveC. You can create swift-based iOS or OSX applications. What you can’t do is write a CLI program that is pure Swift.

Look at any programming language instructional methodology. What’s the second thing they teach? The second? Yes, the second. The first, since K&R, is hello, world.

The second thing that you have people do is prompt for their name and say hello back to them. Output is important, but without input programs are pretty boring. I’m not ignoring the vast and glorious mound of ObjectiveC and by extension C and C++ code that’s accessible to swift, but that’s not the same as being able to create the same things in swift.

Generally, I find swift a compelling language, but today it’s not a first language. I’m hoping that Apple will correct this deficiency in the not too distant future.


So, that was the post. It’s now a week later. Why is it still sitting unpublished? Well, I just wasn’t happy with my conclusion. Having had a bit of a mull, I’ve not changed my mind but I believe that I need to revisit my basic assumption as to what constitutes the baseline for teaching a first computer language.

The idea that to teach a person how to program you should have as little magic at play a possible. What is magic? Elaborate command invocations for one. Just being able to use the word invocation should be enough of a clue. Requiring the construction of things that have nothing to do with the actual language is another. This is probably the aspect that I have the most difficulty with.

“I’ll teach you how to program, but first you’ll need to lash together the user interface.” That would be all well and fine except that print is provided. Why don’t I need to provide a mechanism for stuff to go out if I need to provide one for stuff that comes in?

So, where do we start? The advantage of the pre-GUI age was that there was one true interface to the computer. The way we thought about our programs was dictated by the programming language we used. For a long time after the GUI was introduced we tried to treat our interfaces as extensions of our programs rather than partner environments. Even after we decided that there was sufficient power to run multiple applications at once, we were still mucking about with low-memory globals.

Trying to make the UI an independent entity took the idea of an abstraction penalty to new heights. The things that worked didn’t scale. And, in general, the things that scaled didn’t work. We won’t even talk about speed. Or fragile base classes … I’ll leave GUI evolution posts for another time.

Suffice it to say that the bones of many developers were used to pave the smooth road on which today’s applications travel to get from creator to customer. Somewhere in the process, we went from being a bunch of villages connected by trails to a planet full of complexity and wonder.

So now, we think about desktop, embedded systems, mobile devices, web, distributed systems, databases and games in radically different ways. These ‘once computers’ are now ‘delivery platforms.’ In order to create a product that aims to make use of (or be available on) multiple of these, it is necessary to perform the equivalent of running a restaurant where the staff are all expert in what they do, but each speaking their own language. To complicate matters, sometimes they want to use the same tools in the kitchen (usually the knives) and the customers tend to fight over getting the ‘best’ table.

If I teach someone C, C++, Java, lisp, PHP, python, or [insert language here], I don’t have to teach them the UI language of the system at the same time. With Swift I do. Is this going to complicate things? Probably. Will it take longer? If I want to be sure that they realize that this UI metaphor isn’t ‘the one true’ metaphor, absolutely.

I believe that Swift has a lot of potential. I would hate to see it restricted to being used only in the context of ‘Developing for Apple devices with Swift.’

Read Full Post »

%d bloggers like this: