Swift

 
28
Jan
2016
 

A Modern Network Operation

by Marcus Zarra

When Apple introduced the NSURLSession API, the landscape of network operations changed. In some ways, the new API made things worse as the block API that was added tempts developers to become very sloppy with network calls. The block API makes it trivial to add network calls anywhere in an application. Very little thought or structure is required. From this (and some third party libraries who followed the same pattern) we have seen an explosion of increasingly poor network handling in applications.

For my own purposes I have resisted this slippery slope as often as possible. However I still preferred the way NSURLConnection worked and how it integrated nicely with NSOperation subclasses. My attempts at using the NSURLSession were cumbersome and didn’t feel “right”.

Fortunately, I have recently worked on a design that I have been quite pleased with. In this design I am happily using NSOperation subclasses again and I am using the NSURLSession API.
(more…)

 
14
Dec
2015
 

Swift Type Constrained Extensions: Express Yourself

by Matt Long

I admit it. I was pretty down when Swift was announced. I appreciated the finer points of the reasons for it, however, they weren’t convincing–at least not to me–not at first. I denied that it was actually “expressive” as the overall community was referring to it, however, that was before version 2. It’s at the point when the lights went on for me. I am now a convert and this post explains why–at least one of the reasons. The only question I ask now is while you can do some really cool expressive things, should you? You’ll see what I mean if you read on.
(more…)

 
25
Jun
2015
 

Core Data and Aggregate Fetches In Swift

by Matt Long

You can find other articles on the interwebs about NSExpression and NSExpressionDescription, however, I wasn’t really satisfied with the explanations I’ve seen. I decided to write a post myself after I recently had to become much more intimate with the way Core Data aggregate fetches work. I hope this will make clear what has to be done in order to harness this powerful feature of Core Data.

You’ve heard it said before and sometimes in a scolding tone, “CORE DATA IS NOT A DATABASE. IT’S AN OBJECT GRAPH!”. What normally follows is a discussion about what that means, if you’re lucky. Otherwise, you’re just on your own to go figure it out. In my mind, though, it’s not necessarily wrong to think of it as a database as they have enough things in common to make it a reasonable thing to do and at the end of the day Core Data is backed by a SQLite database. I think that if it helps you understand what is going on behind the scenes better, then go for it. You do have to remember some key differences that can bite you like the need to fetch before updating or deleting, for example. Though with recent additions–last year with iOS 8’s NSBatchUpdateRequest (link to iOS 8 API diff since it’s not currently documented) which allows you to perform a batch update similar to a SQL update query or this year with iOS 9’s NSBatchDeleteRequest (See WWDC 2015 session 220 for more info) which allows for batch deletes based on whatever predicate you give it, the lines seem to be blurring more and more. (more…)

 
2
Dec
2014
 

Beginning iOS Development With Swift

by Matt Long

Many years ago now, I wrote a tutorial for the beginner to learn how to use outlets and actions as this is often one of the least familiar aspects for new developers who are wanting to learn iOS. It’s simple once you’ve seen it, but until then, there’s a gap. This time around I’m presenting an application that is similar to the one I did back then, however, it’s up to date with Xcode 6 and Swift. If you are new to iOS development, this should help get you going.

Beginning iOS Application Development with Swift from Skye Road Systems on Vimeo.

 
5
Nov
2014
 

Swift and valueForKeyPath: You Can’t Keep A Good API Down!

by Matt Long


tl;dr; Download the Value For Key Path Playground


I was incredibly disappointed in Swift when I started to look into how key value coding might be preserved in the transition from Objective-C. Of course, Apple would preserve that, right? And I don’t mean by resorting to using Foundation classes–you know all type-casty and everything (yeah, type-casty). Are we progressing forward or looking to the past, after all? I shouldn’t have to rely on NSArray like this:

var values = (items as NSArray).valueForKeyPath("value")

Right? Who wants to do that? What’s the proper Swift way?

Well, my early assumption from what I was seeing in Swift was that valueForKeyPath: was gone and no longer did we have a convenient way to grab only the fields we needed from a collection of objects. It appeared that it couldn’t be done–at least not in any idiomatic elegant way. Then I downloaded some sample code from the Apple developer site and noticed they were doing what I needed, but using map to do it. The answer was map. Here’s an example:

var lastNames = items.map({$0["last"]! as String})

Now the lastNames variable contains a list of strings with just the last name property of my items array. Given an array of dictionaries like this, you can see how that is providing pretty much what we used to get from valueForKeyPath:

var items = [
    ["first" : "Billy", "last" : "Bogart", "address" : ["street" : "111 Main Street"]],
    ["first" : "Gary", "last" : "Gollum", "address" : ["street" : "2277 AB Street"]],
    ["first" : "David", "last" : "Dangerly", "address" : ["street" : "22311 Place Ave."]],
    ["first" : "Johnny", "last" : "Jones", "address" : ["street" : "10 Orange Rd."]]
]

lastNames now contains:

["Bogart", "Gollum", "Dangerly", "Jones"]

Notice we also have an address property that points to a dictionary. If want to get the street property inside of address, we can drill down the same way:

var streetAddresses = items.map({ $0["address"]!["street"] as String})

Now, you can see we had to force-unwrap the address property in order to access the street property. This works perfectly and is a fine replacement for valueForKeyPath: of old. When the call succeeds we now have all of the street addresses in the streetAddresses array:

["111 Main Street", "2277 AB Street", "22311 Place Ave.", "10 Orange Rd."]

Take a look at the Value For Key Path Playground if you want to see it in action.

What About Safety?

In Objective-C, if you message nil, it’s a no-op. In Swift, however, if we unwrap an optional that is nil, we will crash. So, on this line:

var streetAddresses = items.map({ $0["address"]!["street"] as String})

when we unwrap using the bang ! operator, if that value doesn’t exist, we’re in trouble. Say our data was changed to this:

var items = [
    ["first" : "Billy", "last" : "Bogart", "addr" : ["street" : "111 Main Street"]],
    ["first" : "Gary", "last" : "Gollum", "addr" : ["street" : "2277 AB Street"]],
    ["first" : "David", "last" : "Dangerly", "addr" : ["street" : "22311 Place Ave."]],
    ["first" : "Johnny", "last" : "Jones", "addr" : ["street" : "10 Orange Rd."]]
]

Notice the address field has been changed to addr. This causes a crash.

Playground Crash

Meanwhile, with the old Foundation way, we do this:

var oldStreetAddresses = (items as NSArray).valueForKeyPath("address.street") as NSArray

but look what the output is. NSNull!

[NSNull, NSNull, NSNull, NSNull]

No crash. So which is better?

Well, if your data can be unpredictable, which really shouldn’t happen, then the Foundation outcome is “safer” from a crash perspective. However, your data should be nailed down, so a crash would actually tell you what’s wrong with your data pretty quickly.

What, though, is the safe Swift way of handling this? We can coerce our objects to optionals and use optional chaining instead:

var streetAddresses = items.map({ $0["address"]?["street"] as? String})

So our first optional operator says to return the object or nil and the second operator says that is should be an optional of type String. This call returns an array of optionals that has this output in our playground:

[nil, nil, {Some "22311 Place Ave."}, {Some "10 Orange Rd."}]

Assuming the following data:

var items = [
    ["first" : "Billy", "last" : "Bogart", "addr" : ["street" : "111 Main Street"]],
    ["first" : "Gary", "last" : "Gollum", "addr" : ["street" : "2277 AB Street"]],
    ["first" : "David", "last" : "Dangerly", "address" : ["street" : "22311 Place Ave."]],
    ["first" : "Johnny", "last" : "Jones", "address" : ["street" : "10 Orange Rd."]]
]

Notice the first two use the bad addr field and the last two use the correct address field.

For my applications, I think I would prefer to see a crash so I know my data is bad. It’s the server developer’s problem. Am I right? ;-)

Taking Map() Farther

The map() function really goes far beyond this trivial little valueForKeyPath: replacement example. You can really massage your data into any form you want with it. Say for example you wanted to create an transformed array of dictionaries from your array of dictionaries that had some of the same data, but organized differently. For example:

var fullNames = items.map({ ["full_name" : ($0["first"] as? String)! + " " + ($0["last"] as? String)!] })

This returns an array of dictionaries that contain a single key value pair with a key called full_name and value of the first name and last name of each item in the original array concatenated together. The output looks like this in our playground:

[["full_name": "Billy Bogart"], ["full_name": "Gary Gollum"], ["full_name": "David Dangerly"], ["full_name": "Johnny Jones"]]

As you can see, there really are a lot of possibilities for massaging your data structures using map. The tough part is imagining how it might be used and often that just comes from experience. The more you use it, the more obvious the solutions will become.

Swift Is Not So Bad

There are certain complaints about Swift I still have, however, I am finding that it is growing on me. I am starting to have much more success making my code pure Swift–pulling back from my old habits and considering how problems should be solved in this brave new Swift world. It’s getting better and some of the language aspects are actually better than Objective-C. I couldn’t see that forest for the trees just a couple short months ago. Until next time.

 
29
Oct
2014
 

Protocols in Swift With Core Data

by Matt Long

Sometimes you have a set of objects you want to display in the same form–say, for example, in a table view controller. What if those objects have, by design, nothing in common and nothing to do with each other? This is a case where you can create and conform to a protocol–known in some languages as an interface–to provide a simple way to have each class type provide a display name that can be displayed in your table view controller.

Recently while using this language feature writing Swift code, I ran into a few snags and learned from the process. I figured I would document it in this screencast. It walks you all the way through from project creation, so it’s about 35 minutes.

Here’s what you will learn:

  • How to setup CoreData entities in the data model
  • How to add a run script action to build your managed object classes using mogenerator
  • How to create a protocol in Xcode 6
  • How to implement a protocol in the various managed object classes
  • How to preload your CoreData store with test objects in code
  • How to load each object type generically into a table view controller

And if you want to just cut to the chase, grab the code from github.

Protocols in Swift With Core Data from Skye Road Systems on Vimeo.

 
8
Jun
2014
 

The Core Data stack in Swift

by Marcus Zarra

swift-heroWhenever Apple releases a new version of Xcode one of the first things that I do is look at the default templates and see if there are any new or interesting things.

This year, with the release of Swift, there are some pretty radical changes. Yet the Core Data stack initialization code is still the same.

There is nothing wrong with the default template code but there isn’t really anything right about it either. It is far better than it once was but it is still overly verbose and hard to follow.

Therefore, I present my Swift Core Data stack code that I will be using as I grok this language.

(more…)