Confessions of a Swift Addict

"forgive me father for I have swifted"

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

Every time Apple decided to bring out a new version of Swift, I’d dive headfirst and start the conversion — the sooner the better. None of the past versions were such a nightmare as from Swift 2.1 to 3.0.

These notes I wrote down while converting our project to a Swift 3.0 project. Hopefully someone finds them useful. If you have comments or like to see something added, please let me know.

Let me start with a big fat warning.

⚠️ Don’t ‘Update to recommended setting’. Do this later. ⚠️

So the steps to undertake and achieve Swift bliss are this.

  1. Create new branch.
  2. Change `Podfile` to reflect the following
    platform :ios, '9.0'
  3. Update dependencies with a pod update
  4. Commit changes to git
  5. Convert to Swift 3 syntax
  6. Commit changes
  7. Fix errors (loads of them)
  8. Lint
  9. Commit changes

Breaking changes in Swift 3 Conversion

So first things first – you are not alone in this. Apple has created a good starting point with their migration guide. Read it before starting the conversion and keep it as a reference while converting.

  • New keywords. It takes some getting used to. Current behavior changed too.
  • String indexes and Ranges work different
  • ErrorTypeError
  • All enum cases are now lowercase
  • Use of _ in methods to supres/omit names parameters. Named parameters are now default.
  • .[upper/lower]caseString.[upper/lower]cased() because it is mutating.
  • for can now be used for named parameters .addTarget(self, action: ..., for: ...)
  • containsString()contains()
  • .objectForKey(...)object(forKey: ...)
  • Colors are not a function call anymore but [class var](
  • where keyword in optional binding not needed anymore, you can now just use a comma
  • CGColorRefCGColor
  • when using multiple properties in single guard you must use let for each property. Also in optional binding.
  • UIControlState.NormalUIControlState()
  • UIView.animateWithDurationUIView.animate(withDuration
  • NSFetchedResultsController is now a Generic and must be called with a concrete Type of the Entity you wish to fetch. Like so: NSFetchedResultsController Same with NSFetchRequest(entityName: "Enitity")
  • String(self)String(describing: self)
  • Dispatch Queues tend to f-up the migrator wizard syntax. It mangles it like this: DispatchQueue.main.sync(DispatchQueue.mainexecute: { () -> Void in
    but should have been DispatchQueue.main.sync {
    Swiftable has more info on this


Q: “Argument label does not match any available overloads”
A: In the conversion to Swift 3 something went haywire, look in the original implenmentation wat the function signature is you want to implement.

Q: “Ambiguous reference”
A: You need to provide more Type detail. Usually this is fixed by adding an : Type or an as? Type or with an optional binding if let .... When this method comes from an Objective-C external lib – what also helps is to annotate the Objective-C methods with NS_SWIFT_NAME(method(arg1:arg2:))

Q: “Method cannot be declared because its parameter uses an internal type”
A: Take a close look at the access modifiers. The above states that there are no (and thus internal), or wrong access modifiers used.

Q: “Instance method ‘method(param:)’ nearly matches optional requirement ‘method(in:)’ of protocol ‘SomeProtocol'”
A: In some cases the Swift migrator fails but does find something that looks like that method signature. Usually fixable by searching and copying the orginal protocol for the method signature. In UIKit protocols is almost always the case that you need to supress the param name by adding an underscore to it. So func method(param:) becomes func method(_ param:)

Q: “Expression of type “SomeType?” is unused”.
A: (This answer comes directly from Stack Overflow) Before Swift 3, all methods had a “discardable result” by default. No warning would occur when you did not capture what the method returned.

In order to tell the compiler that the result should be captured, you had to add @warn_unused_result before the method declaration. It would be used for methods that have a mutable form (ex. sort and sortInPlace). You would add @warn_unused_result(mutable_variant="mutableMethodHere") to tell the compiler of it.

However, with Swift 3, the behavior is flipped. All methods now warn that the return value is not captured. If you want to tell the compiler that the warning isn’t necessary, you add @discardableResult before the method declaration.

If you don’t want to use the return value, you have to explicitly tell the compiler by assigning it to an underscore:

_ = someMethodThatReturnsSomething()

Why did this change in Swift 3:

  • Prevention of possible bugs (ex. using sort thinking it modifies the collection)
  • Explicit intent of not capturing or needing to capture the result for other collaborators

The UIKit API appears to be behind on this, not adding @discardableResult for the perfectly normal (if not more common) use of popViewController(animated:) without capturing the return value.
Warning of unused result
SE-0047 Swift Evolution Proposal

API Changes:

Apple keeps a list of API’s that changed, the ones that have a Swift method signature. This way you can cross reference if you get any ‘Instance method nearly matches optional requirement of protocol’ errors.

When you use your own libraries with Cocoapods.

Cocoapods fails when linting.

Errors with Generics

I’ve hit a couple of compiler errors which are already filled with Apple. Try to work around it or find a different solution to your problem. Unless Apple fixes this (which will probably be next version)
Once all your errors are gone and you linted your project with SwiftLintnow you can update to the latest project settings.

Advanced Debugging in Xcode and Swift

I was reading a post by Natasha The Robot about Xcode Debug Tips. (must read!) She talks about a WWDC2015 video ‘Advanced Debugging and the Address Sanitizer‘. This shows a really cool trick for debugging. I took Natasha’s advice and I’d like to show you some more tricks of my own to help you with your debugging.

When running a program things can just crash and Xcode and LLDB are not particularly friendly or verbose about it’s error messages. In Xcode you can have two types of breakpoints: ‘Workspace’ and ‘User’. When adding a breakpoint to ‘Workspace’ it is only visible for that project. But wouldn’t it be cool you set your breakpoints once and they show up in every project you create? ⌃-click on the breakpoint and select ‘Move breakpoint to => user’. Now you have that breakpoint in every project you create in Xcode.


In the above video, they talk about adding a breakpoint and printing the first argument. Which is actually the error message. They do this with ‘po $arg1’.

I’ve taken this example and extended it somewhat. Having a error message is nice, but I would also like to see where that error message comes from. One breakpoint is not bound to one action only – you can set up multiple actions when a breakpoint is hit. you can add sounds or backtraces. The later gives us more information about the crash.

⌃-click on the breakpoint and select ‘Edit breakpoint’, now add two actions. The first is a debugger command with ‘po $arg1’. And click the + to add a new action and select debugger command from the pulldown (if not already selected) and type in ‘bt’. This is the LLDB command for ‘backtrace on the current thread’. (More command for LLDB can be found on their site.). (This should look like the image below)


When compiling again we can actually see where our crash/error is coming from and it a has a more verbose error message.


Happy debugging 🙂

Playing with iBeacons on iOS: A Guide

Unfortunately I had to cut the beacons open to replace the batteryFor the last weeks I’ve been playing with beacons – these are small Bluetooth Low Energy (BLE) devices that broadcast information. iBeacons are Apple’s take on BLE. And i have to say – I’m sold. iBeacons are amazinglysuperduperawesome!

Read the rest of this entry »

iOS Quicky: Securing and dumping data from Keychain

keychainFor one of the latest projects I’m working on we are relying heavily on online/offline usage and storing data in the Keychain (Apple’s safehouse for passwords and other secure stuff). For this I’m using a class provided by Apple called ‘KeychainItemWrapper’.

You can download it from Apple’s site.

My approach was simple; When my view was loaded I would setup the Keychain and under certain circumstances I needed to clear a key/value combo, I would do this.

- (void)viewDidLoad
    self.keychain = [[KeychainItemWrapper alloc] initWithIdentifier:[[NSBundle mainBundle] infoDictionary][@"CFBundleDisplayName"] accessGroup:nil];
- (void)resetKeyChain
    [self.keychain setObject:@"" forKey:(__bridge id)kSecAttrAccount];
    [self.keychain setObject:@"" forKey:(__bridge id)kSecValueData];

Boy was I was dead wrong – it would not clear my keys from the Keychain. Took me hours to find a solution – looking for the proverbial needle in the keychain. (Debugging Keychain is a bitch. Also when deleting an app, the keychain is not cleared, which makes it next to impossible to see changes).
A better approach would be to set up the Keychain like so;

- (void)viewWillAppear:(BOOL)animated
    self.keychain = [[KeychainItemWrapper alloc] initWithIdentifier:[[NSBundle mainBundle] infoDictionary][@"CFBundleDisplayName"] accessGroup:nil];
- (void)resetKeyChain
    [self.keychain resetKeychainItem];

This would clear the appropriate stuff from my Keychain and present my user with a login dialog again. Problem solved 🙂

Day Against DRM 2014

Most of you know I fully support privacy, freedom of speech and am against vendor lock-ins. When I buy something I want to own it, because I paid for it, I want to hack and adjust that object if it does not fit my needs completely an I certainly don’t want to lease it from a vendor.

Just like last year several online book publishers are coming together on the ‘Day against DRM’ – download, keep or share your purchase. And I fully support this! That’s why I’m writing this post.

O’Reilly, who always publishes books without DRM, is doing a massive discount today by offering you 50% off on everything they offer. You can use DRM2014 at the checkout. (Of course I would love it if you picked up a copy of my book 😉

Packt is offering all its DRM-free content at $10 for 24 hours only on May 6th – that’s all 2000+ eBooks and Videos.

So I hope you support this cause too and pick up some great books in the mean time.

Git autocompletion and autocorrect.

At work i use Git *alot*. Most of the time I type too fast and my screen produces jibrish, commonly known as typos. To prevent this frmo happening, there is a fix.
Git itself has a bunch of configuration options to customise behaviour, preferences and visual appearance.

The manual states;


This option is available only in Git 1.6.1 and later. If you mistype a command in Git, it shows you something like this:

$ git com
git: 'com' is not a git-command. See 'git --help'.

Did you mean this?

If you set help.autocorrect to 1, Git will automatically run the command if it has only one match under this scenario.
git config --global help.autocorrect 1
The final parameter to that command is the amount of seconds, unline what the manual states. Setting it to 15 means 1.5 seconds, setting it to 1 means 0.1 seconds.

Git Autocompletion.
Open up Terminal and type in the following;
curl -o ~/.git-completion

This downloads the git-completion script and places it in your home folder.
Open up ~/.bash_profile with your favorite editor and add the following line at the end of it.

source ~/.git-completion

You are now good to go. No open a new Terminal tab or force this command by ‘refreshing’ the terminal by typing source ~/.bash_profile Still in Terminal type git com and press the tab key. This should either autocomplete the command or if there are more commands starting with ‘com’ show you a list of possible options.

Enjoy! No moer typos in Git.

UncrustifyX to use with your Xcode 5 formatting needs

For the past couple of days I’ve embedded myself in Xcode and making the most out of Xcode, using plugins and generally getting to know one another. Yesterday figured out how to do proper code formatting using Uncrustify. I’ve looked at multiple formatting templates and after playing around with several tools, I decided to use UncrustifyX. It is a visual tool to play around and create your own code formatting style. I’ve tweaked, churned and crunched out my own formatting style for others to play around as well which you can find on my GitHub account.

From frustration comes inspiration – Source formatting in Xcode 5+

Tools Workshop[UPDATE: To fix this for Xcode 5.1 – please scroll to the bottom of this page]

From frustration comes inspiration – one of my biggest frustrations while using Xcode is that there is no build in way to do code formatting. Well ok, you do have ‘re-ident’ but that is mostly a manual process and i like using the keyboard. Also this is not quite what I was after.

After some searching I found Uncrustify a generic “Source Code Beautifier for C, C++, C#, ObjectiveC, D, Java, Pawn and VALA”. I checked out the sourcecode, build it and placed the newly created binary in my bin folder. Next up was this Xcode plugin. Easiest and fastest way to get this on your system is by unzipping the binary and placing it in your ~/Library/Application Support/Developer/Shared/Xcode/Plug-ins folder. Don’t forget to restart Xcode after you do this.

After you restarted Xcode, you can open the plugin by navigating to Edit -> Format Code

  • Use the menu Format Selected Files to format the selected items in the project navigator.
  • Use the menu Format Active File to format the source file actually opened in the editor.
  • Use the menu Format Selected Lines to format the selected source code (multiple selection is supported). The selection is automatically extended in full lines. If the selection is empty, it uses the line under the cursor.
  • Use the menu Edit Configuration to edit the formatter configuration in an external editor.
  • Use the menu BBUncrustifyPlugin Preferences to change the plugin preferences.

The real magic happens when you assign it to a key binding. Unfortunately this cannot be done in Xcode and have to be done system wide. So go to System Preferences -> Keyboard. Under Keyboard Shortcuts select ‘Application Shortcuts’ and press the plus sign to add a new program. Select Xcode and call it Format Active File. The naming is very important to be exactly the same as the actual item in Xcode. Naming it differently makes it unusable.
Screen Shot 2014-02-12 at 11.22.07 AM

You can also use different configurations for your own source code. If you create a directory called .uncrustify in your user home directory and check out this repository in that location, you have a very good starting point for your own formatting style. If you have questions regarding the formatting and indentation etc, there is a lot of answers on StackOverflow, be sure to check it out if you want to make your own formatting magic happen.

When you go back to Xcode and you see a key binding next to the Format Selected Files you know everything worked out.


Et voilà! Pressing that key combo adds magic/formats your source code in the flavor you like. Enjoy!

To make this work for Xcode 5.1 find the plugin file, right click on the file and select ‘Show Package Contents’ and open up the Info.plist in a plain text editor. Then look for the key DVTPlugInCompatibilityUUIDs and add A2E4D43F-41F4-4FB9-BB94-7177011C9AED under the last entry. Save and reopen Xcode. Tada!


Adding keybindings in Xcode 5

I’ve been using Xcode for quite a while now, but it still takes some getting used to. Today I had enough and wanted to add my own bindings for “duplicate current line” and “delete current line”, something i’ve been used to in FDT.

I’ve found some resources that help me on my way, so here is a quick reminder/walk through to do it (I don’t take credit for exposing this method, i just use it). It takes about 3 minutes to set up and can save you *a lot* of frustration.

  1. Find IDETextKeyBindingSet.plist in the folder /Applications/ Resources, get the file info and change the rights to “read & write” for user everyone. This allows you to make changes to the file. Now open it in Xcode.
  2. Add a new key as a Dictionary and call it Customized and add a String.
    Screen Shot 2014-02-10 at 1.16.01 PM
  3. As String key add Duplicate Current Line and as value fill in selectLine:, copy:, moveToEndOfLine:, insertNewline:, paste:, deleteBackward:
  4. As String key add Delete Current Line and as value fill in deleteToBeginningOfLine:, moveToEndOfLine:, deleteToBeginningOfLine:, deleteBackward:, moveDown:, moveToBeginningOfLine:. Save file and close and reopen Xcode.
  5. Now go into “Key Bindings” under “Preferences” and press Customized
    Screen Shot 2014-02-10 at 1.15.41 PM
  6. Now give the two newly added key bindings the binding you’d like, i’ve set mine to CMD-D for deleting a line and CMD-SHIFT-D for duplicating a line.
  7. Enjoy!

Code Reviews

code_review5For the last months I’ve been doing a lot of Objective-C. Got a new job and only focus on iOS development. Since I am the new guy in the team, I learn a lot by looking at code from my peers (and looking at code in general). And even though I have a lot of ActionScript experience under my belt, I’m starting fresh with Objective-C. Frustrating at times, awesome most of the time. I love being the new guy. I get to ask dumb questions, can still write silly code and make a lot of beginners mistakes. And challenge my peers by having Shoshin or beginners mind.

One of the things I really love is code-reviews by my peers, they are mandatory at the place I work. They basically go through my code and comment on it when I fuck up or make dumb mistakes. Lately I had to return the reviewing favor.

Looking through code of my co-workers and myself I noticed a couple of things and thought it would make a good bit for an article. I’ll go through as much of the bad stuff I can find and discuss them here. As habits are hard to change, get in the habit of changing them as soon as you see them in your own code. This is by no means a definitive list and if you have suggestions for more, let me know in the comments.

1. Commented Code
Since you use a VCS like Git or SVN, there is absolutely no need to leave commented code in your source files since you can always revert. So remove it.

2. Duplicate Code / KISS
If you have a lot of duplicate code all over the place – you are doing it wrong. KISS and refactor (see point 6.)

3. NSLogs
Since Apple defines logging *only* for errors, a better way to get information from your app is by utilizing your debugger. There have been numerous articles about not using NSLog in (production) code and why it’s better to use a breakpoint. The cool thing about breakpoints in XCode is that you can use non-breaking breakpoints that send a message to the output window.

4. Retarded and/or short unreadable variable names
No matter what language you write code in, you always need to make sure it is readable. For your team members or for yourself when you come back to a project a year from now. This includes the correct naming of variables. Since Objective-C is by itself a very verbose language, variable name tend to have the same tendency. Using myReallyLongVariableName is oke, since compilers nowadays are optimized to deal with this. Verbosity and readability over brevity and difficulty to read code.

5. Small is beautiful
Just like an app or program, methods need to do one thing only and do that one thing well. Like the UNIX philosophy.  That’s what I’m taught and still believe. Don’t bloat your methods with doing six things. This makes it very difficult to read, understand and debug. Small is beautiful.

6. OOP.
What I see *a lot* is that people don’t know how to use proper OO. Not knowing how to extend classes or know how to design to a protocol (Objective-C’s term for interfaces) is basic stuff. Don’t be afraid to ask your peers, even if you’ve are an (iOS) senior.

7. Design Patterns.
While design patterns are not a magical, ready made solution or a silver bullet if you will, i do advise you to get a proper book on design patterns and learn about Model View Controller (MVC), Key Value Observation (KVO) / Observers and Delegation. These are the fundamentals of iOS programming.

8. Refactoring
The problem with writing code is that there is always ego involved. Even in ego-less programming (MUST READ!). That one brilliant solution you created for that one project will look like crap to another team member. People see things in different ways and that is oke. People do things to solve problems. Don’t try to rewrite everything just because it doesn’t look proper to you, try to put yourself in their shoes when they wrote this piece of code you are looking at. And breathe.

9. Lose the Ego
Reality check: Your code is not you. What? Your code is not you. It is just a solution to a problem, even though sometimes a very good solution. Don’t think you are the only one that can have good solutions. I don’t. (Well I actually do, sometimes – but I’m learning) The best solution come from unexpected corners or people. Even veterans make thinking mistakes, I know I do. And lose the ego. Realizing that makes you grow and makes better software.

10. Take responsibility
The next person that says “Nah that wasn’t me that wrote this” will get a kick in the groin. Seriously. I truly believe developers in general need to take responsibility for the code they create. Not taking responsibility is not believing what you wrote in the first place. You do care about your code right? Otherwise you are in this for the wrong reasons. Making a mistake is not the worst thing that can happen, it’s just a piece of code we are taking about. So have some balls.

BONUS. My debugging mantra
As I already mentioned on Twitter some time ago; Bugs are communication errors between you and the machine and can be fixed by asking ‘what do you think i said and why do you think that?’. Taking this step back can help you debug faster.

So. Embrace change, be open, don’t be cocky, loose the ego, look with children’s eyes, have a shoshin mind and enjoy what you are doing – only then will you grow as a coder.