Under The BridgeUnder The Bridge

Musings
Standing on Guard

Here’s a question for discussion that will bring shivers of shared pain to the Swift programmer, no doubt:

Sneaky Swift Tricks: The fake Boolean

Moshe Berman writes, “If I’ve got a bunch of chained guard let statements, how can I diagnose which condition failed, short of breaking apart my guard let into multiple statements? Given this example:

How can I tell which of the 4 let statements was the one that failed and invoked the else block?”

How, indeed? TL;DR There isn’t a really good way. Bah.

However, besides the linked article there’s an active discussion at the Stack Overflow question, and we’d suggest checking on them to see if anything that suits you has shown up, and if not pick up some more Swifty tricks along the way. The one we like the best so far is this gist from AfricanSwift defing the =∅ (null check) debug operator:

If you have a better suggestion, that Stack Overflow question is waiting!

State of JSON Address

So this weekend we’re taking a look at a weather API service that provides data in JSON. So we’re looking around for new and/or notable and/or actively maintained developments in the JSON + Swift world. Always enjoy a good treasure hunt, don’t you?

Particularly nifty thing we stumbled across is JSONExport, which isn’t that new but was to us. If it’s new to you too, check it out:

JSONExport is a desktop application for Mac OS X written in Swift. Using JSONExport you will be able to:

  • Convert any valid JSON object to a class of one of the currently supported languages.
  • Preview the generated content before saving it.
  • Include constructors only, utility methods only, both or none.
  • Change the root class name.
  • Set a class name prefix for the generated classes.
  • Set package name for Java files.

And you have a baker’s dozen options of output for that:

  1. Java for Android.
  2. Java for Android – to use with Realm.
  3. Swift Classes.
  4. Swift Classes – To use with SwiftyJSON library.
  5. Swift Classes – To use with Realm.
  6. Swift – Core Data.
  7. Swift Structures.
  8. Swift – Struct – Gloss
  9. Objective-C – iOS.
  10. Objective-C – Mac.
  11. Objective-C – Core Data.
  12. Objective-C – To use with Realm.
  13. Swift – Mappable [not included in README — ed.]

Convenient! Or perhaps you’d like to handle Core Data serialization more directly? Here’s an option:

Groot: “From JSON to Core Data and back.”

Groot provides a simple way of serializing Core Data object graphs from or into JSON.

Groot uses annotations in the Core Data model to perform the serialization and provides the following features:

  1. Attribute and relationship mapping to JSON key paths.
  2. Value transformation using named NSValueTransformer objects.
  3. Object graph preservation.
  4. Support for entity inheritance

Or here’s another option:

Sync: “ Modern Swift JSON synchronization to Core Data.”

Sync eases your everyday job of parsing a JSON response and getting it into Core Data. It uses a convention-over-configuration paradigm to facilitate your workflow.

  • Automatic mapping of CamelCase or snake_case JSON into Core Data
  • Handles operations in safe background threads
  • Thread-safe saving, we handle retrieving and storing objects in the right threads
  • Diffing of changes, updated, inserted and deleted objects (which are automatically purged for you)
  • Auto-mapping of relationships (one-to-one, one-to-many and many-to-many)
  • Smart-updates, only updates your NSManagedObjects if the server values are different (useful when using NSFetchedResultsController delegates)
  • Uniquing, Core Data does this based on objectIDs, we use your primary key (such as id) for this
  • NSOperation subclass, any Sync process can be queued and cancelled at any time!

If you’re just looking for JSON parsing into objects without the Core Data integration, there’s … a surprising number of helper options these days:

… and a veritable plethora of others. If we and all those collections missed your favorite, let us know!

Some discussions to help you decide which of these if any suits your particular use case best:

How I deal with JSON in Swift

Everything You Need to Know About JSONJoy, SwiftyJSON & OCMapper

Swift JSON Shoot-Out

The state of JSON parsing in Swift – Part 1

Enjoy your paradox of choice!

UPDATES:

Here’s another that generates SwiftyJSON/ObjectMapper friendly classes: SwiftyJSONAccelerator

Alembic: “Functional JSON parsing, mapping to objects, and serialize to JSON.”

Atlas: “An extremely easy-to-use and lightweight JSON mapping library for iOS and tvOS written in Swift.”

Working with JSON in Swift

JSONShootout: “Compare several Swift JSON mappers.”

Rethinking Routers in Swift using Protocol Oriented Programming — Part 1

API Endpoint Testing with Postman

Simulate APIs and Backend Server with New Postman Mock Server Feature

Paw 2 – The Missing HTTP & REST API Tester For Mac

Insomnia Is Now Open Source

Dynamic UI Testing HTTP Mocking

When JSONDecoder meets the real world, things get ugly…

Swift Tip: Networking with Codable

Tip: Swift Common Initializer Pattern

Here’s a handy tip for reducing duplication and/or frustration with your initializers:

Common Initializer Patterns in Swift

Swift has a very well thought-out initializer system in place. With options such as designated and convenience initializers, one must ensure all properties have values since the compiler will make sure of it. Take a look at my other post for more details.

… Your first thought may be: why not wrap it in a function and call the function from both initializers. Nope. Can’t do that because you cannot reference “self” for the method call before calling “super.init“, and you can’t call the method after initialization either until you’ve initialized all properties – catch 22:

So you end up either tedious and violating DRY, or using var/lazy and violating immutability, yes, we find that niggling on a fairly regular basis. Skipping past the narrative (follow the link if you wish) Here Is The Solution:

https://gist.github.com/alexcurylo/db743df00a6d27758b45c6537b26a800

Wow, nice! Solves the redundant code problem while still abiding by the initialization rules. It’s using a static function to initialize the properties, which indeed can be called before the class is initialized (since it’s static and not using self).

Secondly, it’s returning a tuple to initialize multiple properties at once. That’s cool too! And for the sugar on top, it’s using a “typealias” like “My” or “I” to keep the static calls short.

We like it! Very Swifty feeling, isn’t it?

h/t: This Week In Swift!

For another interesting initialization pattern, check out

Swift: Configuring a Constant Using Shorthand Argument Names

It’s a common pattern in Swift (and a really nice one!) to configure constants right when they are initialized in a closure vs later on in a viewDidLoad or another such method … ’ve always found it kind of awkward to name another UIView in the closure. Now there is a “purpleView” and a “view”. Should “view” actually be named “purpleView” also? I haven’t figured out a good solution for the naming problem here. So I was super excited to see the tweet that uses $0 instead of bothering to name the variable!

Not quite sure whether we actually prefer this, but it is more concise. Also check out the Configurable extension from the comments!

Follow The Script

Between writing our client apps in Swift and looking forward to writing our server apps in Swift, we tend to overlook that Swift can be used as a scripting language as well — seriously, is there anything it can’t do? — so here’s how you do that using Xcode:

A Beginner’s Guide to Scripting in Swift

First, you’ll need to start with a new Xcode OS X Command Line Tool Application … The cool part here is that you can even import frameworks like Foundation. Anything you can do with Foundation, you can put into a script — this includes File I/O, string manipulation, and more … Your script can even accept arguments. Just append whatever you want after your execution command to add your arguments like a regular script…

Scripting is a powerful asset and a useful tool in any programmer’s tool belt. For many iOS Devs, Swift or Objective-C are the only languages they know. If they know Swift, then there is no need to learn Python or another scripting language when writing simple scripts for any automation process.

End-to-end development and deployment with nothing but Swift? Shiny!

Another introduction here:

Scripting in Swift

A shell script is perhaps the most popular command-line scripting language, particularly in the mobile development world. To test the viability of scripting in Swift, we’ll write our markdown converter first as a shell script and then compose a Swift version. We’ll then do a quick comparison of the pros and cons of each script…

And one more example from @ayanonagon (and Swift Scripting talk here):

Swift Scripting By Example: Generating Acknowledgements For CocoaPods & Carthage Dependencies

We started using both CocoaPods and Carthage to manage our dependencies, and we wanted to add a nice little view in our app that shows a list of open-source acknowledgements and licenses. We have around 20 dependencies, and the thought of adding the acknowledgements manually sounded tedious…

Indeed it is. Well, that’s definitely our first experiment in integrating Swift scripts into our production process, then!

UPDATES:

Swift Scripting Redux: Localization

Running The Swift 3.0 Migrator On A Standalone Swift File

Command Line Swift

Scriptarian: “allows you to easily automate macOS using the Swift programming language, providing a modern alternative to AppleScript.”

Marathon “makes it easy to write, run and manage your Swift scripts.”

Scripting and Compiling Swift on the Command Line

How to Make a Web Crawler in Swift

Beak: “A command line interface for your Swift scripts”

Third Time Swifty

So you’ve no doubt heard there’s a new Swift coming, and asked yourself

What’s new in Swift 3.0?

Swift 3.0 is changing pretty much everything, and your code will almost certainly refuse to build until you make the necessary changes. Seriously, if you thought the jump from Swift 1.2 to 2.0 was big, you ain’t seen nothing yet.

Didn’t we go through this already … why yes. Yes, we did.

In this article I’m going to explain some of the most important changes with as many code examples as I can, and hopefully this will give you some chance to be prepared to update your code when Swift 3.0 goes final. There are many more changes than the ones listed below, but the changes below are the ones that are most likely to hit you…

It’s like the Guaranteed Swift Programmer Employment Act! But don’t get too worked up, we completely agree with the conclusion of that article:

It’s easy to read these changes, some of which are tiny but introduce massive breakage, and imagine that Apple’s Swift engineers are just out to make our lives harder. However, the truth is that they are working hard to make sure Swift is as easy to learn, easy to use, and fast as possible, which are three very different priorities.

In particular, I have been struck by how committed the Apple team are to ensuring their changes are discussed and agreed in the open, as part of the Swift Evolution community effort. Every change above went through extensive community discussion before being agreed for Swift 3.0, which is an incredible thing to behold.

You can get involved and help shape these changes going forward: they are keen to hear ideas from a wide range of users, and it means the future of Swift really is in your hands.

So yes. If you’re writing or maintaining Swift code — and who isn’t? — we MOST strongly recommend you read this article thoroughly, and soon. Even better, get an early jump with How to install Swift 3 today and this sample project for instance. Although we’d figure that a Swift 3 running Xcode is pretty likely to show up first day of WWDC 2016, so no need to get too worked up there.

Speaking of the evolution of Swift, there’s also been a great deal of heartfelt concern voiced recently about a) ABI compatibility being missed in 3.0, and b) Swift never getting @objc on its cross-platform incarnations as the current plans lack, and what that lack of runtime dynamism means. (Spoiler: Horrible things.) Around here, we’re just fine with a) taking as long as it takes to get right, and with b) we’re pretty sanguine that something functional (geddit?) which fits the Tao of Swift will show up to address common use cases; but others find it a far more pressing concern. Great round up by Michael Tsai:

Dynamic Swift

Read that if you need to get involved in a good internet fight! Or even if you’re not, there’s still a lot of good conceptual discussion there, if you’ve got some time being familiar with the debate is worthwhile we’d say.

And speaking of being familiar with the debate, prepare yourself for Swift advocacy by checking out

Why big apps aren’t moving to Swift (Yet)

I strongly believe Swift is the future of iOS development. It’s only a matter of when, and the blocker is the breakneck speed it evolves. For smaller apps, Swift is good enough. For big apps, it’s at least a year away…

Let’s all see what we can do to push that forward!

UPDATES:

Wil Shipley smacks down the griefers in Pimp My Code, Book 2: Swift and Dynamism

How To Install New Swift Versions in Xcode

@ayanonagon’s Favorite Swift 3.0 Features

Ole Begemann’s Swift 3

littlebitesofcocoa.com #243: The Great Swift 3 Rename 🐤

What’s new in Swift 3.0

What’s New in Swift 3 – Part 1 and Part 2 and Part 3

Swift 3 and Declarative Programming

Official Swift Blog: Swift 3.0 Released!

Swift 3 Notes

Optional Non-Escaping Closures

Objective-C id as Swift Any

Updating Strings for Swift 3; Mastering Swift: essential details about strings  

Swift 3 Conversion Steps. Or “The 9 steps to Swift bliss”

Swift 3.0 Unsafe World

Writing Libraries for Swift 2.x and 3.0 Compatibility

Grand Central Dispatch (GCD) and Dispatch Queues in Swift 3

Yammer iOS App ported to Swift 3

Swift 3 and Comparing Optionals

A (mostly) comprehensive list of Swift 3.0 and 2.3 changes

Tip: Adding Fields To Interface Builder

Here’s a neat trick that might have never occurred to you — it didn’t to us, anyways:

How to use Xcode to set a text field’s maximum length, Visual Studio-style

There’s the [Visual Studio] GUI builder way…

  1. Select the text box.
  2. Set its MaxLength property in the Properties pane.

… when developing Objective-C and Swift applications in Xcode:

There isn’t a GUI builder way — just a code way, and it’s a little more work than it needs to be…

… That’s a lot of work. Isn’t there a way we can get a “max length” property for text fields, like the .NET people?

And why, yes. Yes, there is! The trick is simply to create an @IBInspectable extension on UITextField:

Swift extensions let you add new functionality to existing classes, structs, enumerations, and protocols. We’re using an extension to UITextField to add two things:

maxLength, a property that lets the programmer set and get the maximum length of a text field, and

limitLength, a method called whenever the contents of a text field are changed, and limits the number of characters in that text field.

Look over the rest of the article and download the sample project for an explanation of the techniques used here. Mighty handy for extending built-in types if you like doing your interface work graphically in Interface Builder … and who doesn’t?

Fire Up The Base

In case you’ve been floundering about what to do service side since Parse dropped the BaaS, here’s something you’ll want to take a look at — Google has seriously levelled up Firebase with unification and new services:

FireBaseServices.png

Firebase is expanding to become a unified app platform for Android, iOS and mobile web development. We’re adding new tools to help you develop faster, improve app quality, acquire and engage users, and monetize apps. On top of this, we’re launching a brand new analytics product that ties everything together, all while staying true to the guiding principles we’ve had from the beginning:

  • Developer experience matters. Ease-of-use, good documentation, and intuitive APIs make developers happy.
  • Work across platforms. We’ll support you whether you’re building for iOS, Web, or Android.
  • Integrate where possible. Firebase has one SDK, one console, and one place to go for documentation and support…

That’s a lot of features there, with free to minimal pricing until you’re scaled up looks like.

Particularly interesting is that they’ve put at the centre there this new analytics service,

At the heart of Firebase is Firebase Analytics, a free and unlimited analytics solution. Analytics integrates across Firebase features and provides you with unlimited reporting for up to 500 distinct events that you can define using the Firebase SDK. Firebase Analytics reports help you understand clearly how your users behave, which enables you to make informed decisions regarding app marketing and performance optimizations…

Custom audiences can be defined in the Firebase console based on device data, custom events, or user properties. These audiences can be used with other Firebase features when targeting new features or notifications.…

As it happens, we’d just been planning to get around to picking an analytics platform for the next project, as it’s been a hella long time since we last surveyed that space, or even updated with notes on the general consensus:

If marketers are going to be using analytics tools, Mixpanel or Localytics. If developers want data to play with, Flurry.

Since then, Flurry was absorbed into Yahoo Mobile Developer Suite, Localytics and Mixpanel appear to be doing fine although now we have actually accurate marketing analytics from Apple,

App Analytics is Apple’s very own analytics platform. It lives right inside of iTunes Connect. Announced at the WWDC in summer 2014, it launched finally in spring 2015 and just recently added support for tvOS apps. One might say just “another” analytics platform like free solutions from Flurry/Yahoo Mobile, Google or Facebook, but App Analytics finally provides reliable data nobody else can (Spoiler: App Store impressions, referring websites, attribution)

You should read all the rest if you aren’t familiar with it, but since it requires no technical implementation there’s no support decision to be made there so we can move on. Let’s check a couple curated collections:

Apptamin’s App Analytics Tools Round-up

iOS Dev Tools’ Analytics section

awesome-ios’ Analytics section

Well, clearly if you have trouble reaching a decision, ARAnalytics is for you:

ARAnalytics is an analytics abstraction library offering a sane API for tracking events and user data. It currently supports on iOS: Mixpanel, Localytics, Flurry, GoogleAnalytics, KISSmetrics, Crittercism, Crashlytics, Fabric, Bugsnag, Countly, Helpshift, Tapstream, NewRelic, Amplitude, HockeyApp, HockeyAppLib, ParseAnalytics, HeapAnalytics, Chartbeat, UMengAnalytics, Librato, Segmentio, Swrve, YandexMobileMetrica, Adjust, AppsFlyer, Branch, Snowplow, Sentry, Intercom, Keen, Adobe and MobileAppTracker/Tune…

And if you’d prefer to just follow the herd, looks like they’re heading for Twitter these days:

Answers Named #1 in Mobile Analytics for iOS

Back in May, Answers was ranked as #2 on iOS and #3 on Android in the mobile analytics space by SourceDNA, the world’s largest database of mobile app intelligence. Since then, we’ve been building out new features like Answers Events, which helps you track specific actions and events in real time, to better understand how users are behaving within your app.

Today, we’re thrilled to tell you that Answers has now been named the #1 most implemented mobile analytics SDK on iOS — just five months after it was named #2!

So no lack of innovation in that space, definitely. If you decide to jump on the new Firebase bandwagon, be sure to let us know how it goes for you!

UPDATES:

Getting Started with Mobile Analytics

28 Metrics That Matter for Your App

Firebase 101, a simple todo list app

Creating a Backend for Your iOS App Using Firebase

Google’s Firebase developer platform gets better analytics, crash reporting and more

Introducing Firebase with Swift 3: Login and Sign Up; Using Firebase to Integrate Facebook Login in iOS Apps

Keep an eye on the competitive developments over at Microsoft: The Next Generation of HockeyApp

Firebase Tutorial: iOS A/B Testing

Fabric lands top spots for app analytics, stability, and monetization

Well, that makes the decision process simpler: Fabric, R.I.P.

Marco Arment:

iOS devs: Any decent self-hostable crash reporters, analytics packages?

I think it’s wise to consider bringing this in-house these days.

Quick-Chat: “Real time chat app written in Swift 3 using Firebase”

Back-End as a Service for Mobile Apps

Implementing Push Notifications on iOS with Firebase

Using Firebase Cloud Messaging for Remote Notifications in iOS

Advanced Firebase For The Win

Firebase Costs Increased by 7,000%!

Get Started With Firebase for iOS Apps

Compleat Pattern Matching

There’s a great series just wrapped up over at Crunchy Development which dives deeper into Swift pattern matching than you’ve ever been, no doubt:

Pattern Matching, Part 1: switch, enums & where clauses

(note that Where “where” may be used? is everywhere, pretty much)

Pattern Matching, Part 2: tuples, ranges & types

Pattern Matching, Part 3: Custom pattern matching & syntactic sugar

(more thoughts on the ? in Matching with Swift’s Optional Pattern)

Pattern Matching, Part 4: if case, guard case, for case

Check out how expressive pattern matching can get by the end of that:

This look might look a little complex, so let’s split it down:

  • It uses map to transform the Array<Media> array mediaList into an array of tuples [(String?, String)] containing the title (if any) + the kind of item (as text)
  • It only matches if title? matches — which is syntactic sugar to say if .Some(title) matches — the $0.title of each media. This means that it discards any media for which $0.title returns nil (a.k.a. Optional.None) — excluding any WebSite in the process, as those don’t have any title)
  • Then it filters the results to only iterate on those for which title.hasPrefix(“Harry Potter”) is true.

Also note particularly in Part 3 about defining the ~= operator for your own types. Which, in case you were wondering,

The pattern matching operator is pronounced “twiddle-eek” not “bacon rocket”. Not only more fun to say but tells you the order in which to type the symbols.

Now you know!

UPDATES:

Swift Enumerations

Beware Visitors Bearing Tints

TL;DR — Set your tint colors explicitly if you have many peer views, and dupe this:

rdar://26227380 UITintColorVisitor causes exponentially worsening performance when adding subviews

When adding subviews to a view that obtains its tint color from the window or a parent view performance gets exponentially worse the more subviews you add. When adding 6000 subviews execution takes over 10 minutes in the following method chain…

If you want a most excellent walkthrough of how to identify that kind of problem in object code, check out

Investigating the Cause of Quadratic Time Complexity When Adding Subviews in UIKit

We like our custom tint color; but not enough to justify such an impact on performance. By deactivating the custom tint color we bring the overall run time of viewDidAppear from our example project from over 700ms down to ~10ms…

The walkthrough of zeroing in on said cause goes through identifying the culprit with the time profiler down to sleuthing through its assembly and ending up as a practical tutorial in the use of Hopper Disassembler (which you may remember us mentioning Mike Ash’s posts on ages ago; also see Hopper + lldb for iOS Developers: A Gentle Introduction) to provide pseudocode for object code you don’t own, concluding

When I started out diving into this issue I was almost entirely clueless about how to interpret complex disassembled code – now I’m still mostly clueless. However, I learned a few very handy tricks along the way:

I learned how to set breakpoints in private methods & and at any address within the assembly code.

I learned about the i386 and Objective-C calling conventions, e.g. which arguments are stored in which registers.

I learned that the addresses in Hopper match the addresses in the actual framework code (besides a base pointers offset depending on where UIKit is loaded into memory). In hindsight this sounds obvious but it definitely was not the case when starting out. This article was very helpful in getting more comfortable with working with lldb in UIKit alongside of Hopper.

These three tools allowed me to explore the code paths & relevant variables a lot faster which in turn made it a lot easier (yet still hard) to get a grasp of what was going on.

In the end I didn’t find a definite answer on how this issue could be fixed, but I found a lot of clues about how the current visitor pattern is implemented and I think I got fairly close to the underlying issue.

Most importantly I learned how to be more efficient at exploring the inner workings of closed source frameworks which will surely come in handy in future!

Yes, that’s a bag of tricks definitely worth adding to your toolkit!

h/t: @jesse_squires, Michael Tsai!

Anticipating Unanticipated Errors

Great article over at Cocoa with Love on structuring Swiftily elegant error handling:

Presenting unanticipated errors to users

The best approach for presenting error conditions to the user is to integrate feedback into the user interface about the condition that the error indicates. This could be changing an icon, colors, adding status text or otherwise changing the state of a user interface element.

This “best approach” requires that we understand the error condition and plan for it in advance.

What if we’re still implementing the app and haven’t had time to exhaustively discover possible error conditions and plan for them? What about technically possible error conditions that we cannot trigger in our own testing making planning impractical? What about error conditions that should never occur if everything is well behaved but are still semantically possible?

We need a base level tier of error handling and reporting to the user. This base level must be very low overhead (so we can add it use it without much thought during development) and while it must report an error to the user, it is primarily intended to gather diagnostic information so the source of the error condition can be understood and facilitate fixes and other maintenance…

The idea is that we end up with runtime-presented information along the lines of

error_dialog2.png

where “Copy Details” provides a full stack trace. Sound interesting? Read the whole thing! And grab the code from the CwlUtils repo on Github!

While we’re on the topic, assertions are an excellent way to anticipate those unanticipated errors; can you name the five types of Swift assertions and enumerate the differences between them? If not, check out (h/t Swift Sandbox):

Andy Bargh’s Swift Assertions

… Not only do assertions allows us to articulate our critical assumptions within code they also help us to design code that ensures the conditions leading up to those assertions are highly unlikely, whilst simultaneously providing us with flexibility and control over when those assertions are enforced.

In some cases, developers advocate that you should only use assertions when developing and debugging, whilst others recommend leaving them in in production as well. My personal preferences lean toward the latter of these two camps. My view is that although triggering an assertion failure is not good, and is definitely not a great experience for end users, I would far rather know about the failures and attempt to fix them, either though additional handling and checking in our code or redesigning things so ensure that the situations leading up to the assert failures don’t occur. For me I feel that this is a better approach to improving the quality of my applications.

We’re totally on board with that. And you should be too!

UPDATES:

Mobile UX Design: User Errors