Favorite Swift Tips & Tricks of 2014

To celebrate the end of the year and the first 6 months of Swift, we asked ten of our Swift-est friends for their favorite Swift tips & tricks of 2014. Thanks to everyone for sharing!

Natasha Murashev

iOS Engineer at Capital One and blogger at Natasha The Robot

Swift allows for a much more functional programming approach when structuring iOS applications, so I’ve been learning a lot about functional programming in order to make better decisions for my Swift code. Here are some of my favorite functional swift resources so far:

Functional Functions - This one easy change to your functions will make your code a lot more independent and testable.

Wrapper Types - I love how readable and safe typealiasing can make code

The Design of Types - More on designing your program with the right types! “Designing the right types for your problem is a great way to help the compiler debug your program”

Practical Use for Curried Functions in Swift - In Haskell, a function can only take one parameter! While Swift is not that extreme, it does allow for “currying” or partially applying a function, which leads to more re-useable pieces of code.

Error Handling in Swift: Might and Magic - I love the simplicity, readability, and safety of this approach to error handling, especially compared to what we usually do in Objective-C.

Railway oriented programming (video here) - This is in F#, but it’s a great way to think about error handling in code - just design for the happy path!

Functional Programming in Swift - This is a bit more advanced book on the functional swift topic, but I’ve found myself finding something new here every time I re-read it. Great for those who’d like a lot more depth and exposure into functional world and how to apply the concepts to iOS code.

Watch Natasha’s video: Building TableViews in Swift & iOS8

Chris Eidhof

Creator of objc.io and Functional Programming in Swift

Functional Quicksort — the following variant of Quicksort will definitely not win any speed prize. Most real implementations of Quicksort will use constant memory. This snippet, however, is one of the shortest and clearest ways to write Quicksort:

func qsort(input: [Int]) -> [Int] {
    if let (pivot, rest) = input.decompose {
        let lesser = rest.filter { $0 < pivot }
        let greater = rest.filter { $0 >= pivot }
        return qsort(lesser) + [pivot] + qsort(greater)
    } else {
        return []

It builds on the decompose snippet: if the array is not empty, it uses the first element as the pivot, and seperates the array into two new arrays: the first containing only smaller elements, and the second containing only larger (or equal) elements. Then it sorts the smaller elements, appends the pivot element, and finally appends the sorted larger elements.

Originally appeared on http://www.objc.io/snippets/3.html

Watch Chris’ video: Functional Programming in Swift

Austin Zheng

Senior Software Engineer at LinkedIn

A nifty (if rather useless) Swift trick that I like is the fact that you can set a delegate to an instance of an anonymous class by creating a closure that defines a conforming class, having that closure return a new instance of that class, and running the closure. That sounds complicated, and so I have a bit of sample code here.

You can watch Austin’s videos: Swift: Enums, Pattern Matching & Generics & Lessons Learned Building “2048” in Swift, or check out his blog.

Clay Smith

Senior Software Engineer at PagerDuty

Here’s my essential bash alias for dealing with all problems xcode (and particularly sourcekit issues):

alias sourcekitsad='rm -rf ~/Library/Developer/Xcode/DerivedData'

You can watch Clay’s 12 Apps of Swiftmas video, or check him out on GitHub.

Michael Helmbrecht

UX designer and iOS developer at Motiv

Favorite bit of trivia would probably be that String does not conform to Printable, so there’s technically not a guarantee that string interpolation works with a String. I think it only works because String is bridged to NSString, which does have a -description method.

You can watch Michael’s 12 Apps of Swiftmas presentation, or check out his blog.

David Kobilnyk

Software engineer at ShopRunner.

Swift seems elegant enough as a language that I don’t particularly find myself needing to hack with special tricks. I do like using enums together with raw types, like this:

public enum ReminderTimeType: String {
    case Evening = "this evening"
    case Tomorrow = "tomorrow"
    case Weekend = "this weekend"
    case NextWeek = "next week"
    case CoupleWeeks = "in a couple weeks"
    case CoupleMonths = "in a couple months"
    case Someday = "someday"
    public static let array = [
        Evening, Tomorrow, Weekend, NextWeek, CoupleWeeks, CoupleMonths, Someday
    public static let rawArray = array.map { $0.rawValue }

You can watch David’s video: Converting Objective-C to Swift, or check him out on GitHub.

Alexis Gallagher

Senior iOS developer

My favorite piece of Swift trivia, trick, resource, or anything? My two favorite tricks of the moment: On the REPL, the handy function

func typeof<T>(@autoclosure () -> T) -> Any.Type { return T.self }

can be used to get the static type of an expression without evaluating the expression. And the undocumented private function _stdlib_getDemangledTypeName can be used to get the type name of any instance value.

You can watch Alexis’ 12 Apps of Swiftmas presentation, or follow him on Twitter @alexisgallagher.

JP Simard

iOS Engineer at Realm

You can get all the private Swift standard library functions by digging through libswiftCore.dylib using the nm tool like this:

cd `xcode-select -p`/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx
nm -a libswiftCore.dylib | grep "T _swift_stdlib_"

Which reveals some very useful functions like _stdlib_getTypeName(), _stdlib_demangleName() and _stdlib_conformsToProtocol() among a few others.

You can watch JP’s videos: Swift for JavaScript Developers & Swift for Rubyists.

Warren Moore

Author of Metal By Example

This is kind of a hack, but it turns out that Swift allows you to treat a homogeneous array of structs as a pointer to the member type of the struct, when all the members of the struct are of the same type (e.g., Float). I use this to succinctly create Metal buffers of vertex data without a lot of unsightly casting.

Mustafa Furniturewala

Software Engineer at Coursera

My favorite Swift resource is this: Swifter (great reference guide when I’m coding)

Favorite piece of Trivia: You can enable dynamic dispatch on any swift func to enable objective-C style dynamic dispatching.

Get more development news like this

About the content

This content has been published here with the express permission of the author.

Natasha Murashev

Natasha is secretly a robot that loves to learn about Swift and iOS development. She previously worked as a senior iOS Engineer at Capital One in San Francisco, but now she travels around, writing about her experiences with new technologies. In her free time, she works on personal projects, speaks at meetups and conferences, contributes to open source, and likes to cross things off her bucket list.

Chris Eidhof

Chris Eidhof is the author of many iOS and OS X applications, including Deckset and Scenery. He has also written extensively on the subject, from his personal blog to objc.io to a variety of books. He formerly ran UIKonf, and still runs frequently.

Austin Zheng

Austin writes software and tries to spend his time learning new things. Sometimes he’ll write about these new things on his blog.

Michael Helmbrecht

Michael designs and builds things: apps, websites, jigsaw puzzles. He’s strongest where disciplines meet, and is excited to bring odd ideas to the table. But mostly he’s happy to exchange knowledge and ideas with people. Find him at your local meetup or ice cream shop, and trade puns.

David Kobilnyk

David Kobilnyk

Entrepreneur in Residence at Samsung Accelerator. Victor of an interesting quest: to convert all the Objective-C code samples in the seminal book “iOS Programming: The Big Nerd Ranch Guide” to Swift.

Alexis Gallagher

Alexis is as an independent consultant, building all sorts of systems with Swift, Clojure, bash, a heartfelt sincerity, a nagging skepticism, and the motley wisdom from his past adventures in science, finance, and comedy.

JP Simard

JP works at Realm on the Objective-C & Swift bindings, creator of jazzy (the documentation tool Apple forgot to release) and enjoys hacking on Swift tooling.

Warren Moore

Warren is a Cocoa developer and occasional trainer, speaker, and blogger. He works at Apple as a Metal Ecosystem Development Engineer, guiding the next generation of 3D graphics technologies.

Mustafa Furniturewala

Mustafa Furniturewala

Mustafa works on the Learning Experience at Coursera. He previously helped build apps at Twitter, Evernote, Klout, and Citrix.

4 design patterns for a RESTless mobile integration »