Swift Developer News - Hacking with Swift News, tips, and tutorials from Hacking with Swift https://www.hackingwithswift.com/articles/rss (c)2017 Paul Hudson https://www.hackingwithswift.com/favicon-96x96.png Swift Developer News - Hacking with Swift https://www.hackingwithswift.com/articles/rss NSAttributedString by example https://www.hackingwithswift.com/articles/113/nsattributedstring-by-example https://www.hackingwithswift.com/articles/113/nsattributedstring-by-example Format text in a variety of ways with this one useful class Fri, 25 May 2018 22:48:30 +0000 Regular Swift strings are great for storing plain text, but as soon as you want formatting, images, or interactivity you need to reach for NSAttributedString - Foundation’s all-in-one string handling class. These are used in lots of places in iOS, but you're most likely to want to use them with UILabel and UITextView – both of which accept attributed strings directly.

In this article I want to walk you through some examples of what NSAttributedString is capable of: creating strings by hand, adding and enumerating attributes, adding links and images, and more. All these code samples are written to work with a Swift playground, which is a particularly good place to try out attributed strings because Xcode can render a preview of how the string looks.

Creating attributed strings

Let’s start with the most trivial attributed string: one that holds a regular string with no special styling. Try this in a playground:

let quote = "Haters gonna hate"
let attributedQuote = NSAttributedString(string: quote)

When that runs, click the preview button for attributedQuote and you should be able to preview it. It doesn’t look special – in fact, it looks just like a regular string – but that’s because we haven’t applied any styling yet.

Try this instead:

let quote = "Haters gonna hate"
let font = UIFont.systemFont(ofSize: 72)
let attributes = [NSAttributedStringKey.font: font]
let attributedQuote = NSAttributedString(string: quote, attributes: attributes)

Now we’re asking for the same text to be rendered in a 72-point font, so your preview should be much larger.

What you put in the attributes is down to how the string should look. For example, this will color the text red:

let font = UIFont.systemFont(ofSize: 72)
let attributes: [NSAttributedStringKey: Any] = [
    .font: font,
    .foregroundColor: UIColor.red,
]

Alternatively, this will color the text white and give it a red glow:

let font = UIFont.systemF...
]]>
The Ultimate Guide to WKWebView https://www.hackingwithswift.com/articles/112/the-ultimate-guide-to-wkwebview https://www.hackingwithswift.com/articles/112/the-ultimate-guide-to-wkwebview Get WebKit into your app the easy way Thu, 24 May 2018 22:22:05 +0000 WKWebView is a powerhouse on iOS, providing high-performance web rendering wherever and whenever you need.

In this article I’ve put together 15 of the most common use cases for WKWebView, providing hands-on code solutions for each of them. So, if you want to solve a specific problem, or if you just want to see what WebKit is capable of, read on!

1. Making a web view fill the screen

Sometimes you’ll see folks add code to viewDidLoad() to create a web view then make it fill all available space. This is inefficient, and also far harder than it needs to be.

A simpler approach is to add a property to your view controller like this:

let webView = WKWebView()

Then overriding the loadView() method to assign that to your view controller’s view, like this:

override func loadView() {
    self.view = webView
}

Having a dedicated webView property is helpful so that you can reference its properties and methods more easily.

2. Loading remote content

Given that one of the major uses for WKWebView is to load remote content, it’s weirdly not just one line of code. Instead, you create a URL from a string, wrap that in a URLRequest, then ask the web view to load that:

if let url = URL(string: "https://www.apple.com") {
    let request = URLRequest(url: url)
    webView.load(request)
}

If you intend to load URLs a lot, you might find it easier to wrap that behavior inside an extension:

extension WKWebView {
    func load(_ urlString: String) {
        if let url = URL(string: urlString) {
            let request = URLRequest(url: url)
            load(request)
        }
    }
}

Now you can load a website just by running webView.load("https://www.apple.com").

3. Loading local content

WKWebView can load any HTML stored in your app bundle using its loadFileURL() method. You should provide this with a URL to some HTML file that you know is in your bundle, along with a...

]]>
Interview: Erica Sadun https://www.hackingwithswift.com/articles/111/interview-erica-sadun https://www.hackingwithswift.com/articles/111/interview-erica-sadun We chat about Swift Evolution, the community, and Clarus the dogcow Wed, 23 May 2018 19:31:33 +0000 No matter which of Apple’s platforms you’ve developed for, you’ve almost certainly come across the name Erica Sadun before. If you haven’t, it’s my pleasure to introduce you to her: she’s authored or coauthored more Swift Evolution proposals than anyone else, she’s written more books than I can count on building great apps using Swift and Objective-C, and she’s also a leading blogger in our community.

Erica was kind enough to take a break from her busy schedule to chat with me about her books, her work in the Swift Evolution community, and, er, dogcows.

Hacking with Swift: Perhaps excluding a few Apple folks, you’re probably the most well-known member of the Swift community. You’re also one of the (comparatively) few folks who were interested in Apple development before the SDK shipped. For the handful of folks in remote parts of the world that haven’t heard of you before, where did your Apple coding interests start?

Erica Sadun: What a kind introduction! Yes, I've done lots of development in the Apple world and had the pleasure of developing for the iPhone before an official SDK released. It was an especially exciting time in my life. I'm getting to relive that excitement a little due to the introduction of Swift.

While the Swift Programming Language is synonymous with Chris Lattner, who is surely the most well-known member of this community, I'm very pleased with the books I've written about Swift. My "Swift Style" book surveys standards used throughout our community and helps you work on establishing a "house style" of your own. "Swift Documentation Markup" book dives into code-level documentation and shows you how to structure and annotate to match your code to Apple's standards.

If you count NeXT development, I've been doing Mac in some form or another since oh say the 80's.

As for Apple Interests, I've been working on Mac development since approximately the time that dinosaurs roamed the earth. I started back in the old days with Pascal and Prototyper,...

]]>
Build a unit converter for tvOS https://www.hackingwithswift.com/articles/110/build-a-unit-converter-for-tvos https://www.hackingwithswift.com/articles/110/build-a-unit-converter-for-tvos Use UIKit and Swift to find out how many inches are in a parsec Wed, 23 May 2018 19:16:58 +0000 Part 1 in a series of cross-platform Swift apps. You can read these in any order you want – each article builds the same app on a different platform, but all are standalone tutorials too.

  1. Build a unit converter for macOS
  2. Build a unit converter for watchOS
  3. Build a unit converter for tvOS

If you can build iOS apps, you can build tvOS apps too. That’s not an exaggeration: not only does Swift provide a shared language, but the two platforms also share a huge range of frameworks – Core Graphics, Core Image, Core Animation, MapKit, WebKit, Auto Layout, and more all work almost identically on both iOS and macOS.

As for their user interface, the two aren’t identical but are certainly hugely similar. At their core, both tvOS and iOS use UIKit, but tvOS is missing a handful of components that don’t work well using the Apple Remote – UISwitch, UIPickerView, UISlider, and UIStepper are absent, for example.

In their place, tvOS has the focus engine: a unique way of letting users navigate around using indirect touches on their remote. For the most part this does The Right Thing, but if you develop more complex apps you’ll need to learn more about guiding it.

I already wrote a whole book teaching how to make tvOS apps (yes, it’s fully updated for the latest version of Swift, and actually comes with lifetime updates for free!), but in this article I’m going to take a different approach to the book.

Rather than teach you tvOS programming from scratch, we’re just going to dive into a real-world project and see how we get on. This will mean you having to learn a variety of things at once (the book is paced more carefully), but on the flip side it will give you a pretty clear idea of whether tvOS programming is for you or not.

In this project we’re going to solve a classic introductory problem with a twist. One of the first things I...

]]>
Five useful methods of dictionaries https://www.hackingwithswift.com/articles/109/five-useful-methods-of-dictionaries https://www.hackingwithswift.com/articles/109/five-useful-methods-of-dictionaries Filtering, mapping, capacity, and more! Tue, 22 May 2018 22:49:41 +0000 Dictionaries are one of Swift’s most commonly used types, so it’s worth taking a few minutes to get to know them a bit better – even discovering one or two new techniques can make a big difference to your projects.

In this article I want to introduce you to five dictionary methods that deserve to be used more. None of them are complicated, so you should be able to read this whole thing in under ten minutes.

1. Transforming values

You should already be familiar with the map() method of sequences (if not, see here), but it’s less useful with dictionaries because it’s possible you might create a duplicate dictionary key as part of your transformation.

As a result, dictionaries get a bonus method called mapValues(): this transforms each value inside a dictionary, putting the transformed result into a new dictionary using the original keys. This gives us the transforming behavior of map() without the risk of duplicate keys.

As an example, here’s a dictionary of strings and integers that store results from an exam:

let results = ["Meghan": 80, "Chris": 90, "Charlotte": 95]

If we wanted to format those values into strings, we could use mapValues() like this:

let formattedResults = results.mapValues { "Score: \($0)" }

Once that runs, Meghan’s value will be “Score: 80” rather than just 80.

2. Intelligent merging

If you have two dictionaries of the same type and want to merge them into a single array, you might be tempted to try this:

let first = ["a": 1, "b": 2]
let second = ["c": 3]
let third = first + third

Sadly that doesn’t work, because Swift can’t tell whether it will result in duplicated keys. Instead, you should use the merge() and merging() methods – the former merges one dictionary with another in place, and the latter returns a new dictionary.

These methods are possible because they accept a second parameter: a closure that is able to reso...

]]>
How to use regular expressions in Swift https://www.hackingwithswift.com/articles/108/how-to-use-regular-expressions-in-swift https://www.hackingwithswift.com/articles/108/how-to-use-regular-expressions-in-swift Match a variety of text using NSRegularExpression Mon, 21 May 2018 22:23:59 +0000 Regular expressions allow us to run complex search and replace operations across thousands of text files in just a handful of seconds, so it’s no surprise they have been popular for over 50 years.

In fact, I consider regular expressions such an important skill for developers that they form one of four components in a book I wrote to help teach critical meta-coding skills, along with Unix commands, Git source control, and Scrum.

You can find out more about that book here, but in this article I want to give you a primer in using regular expressions in Swift. I wrote about the basic technique previously, and here we're going to go further and walk through some of the most important regular expression syntax along with some useful extensions to make them more convenient.

 First, the basics

Let’s start with a couple of easy examples for folks who haven’t used regular expressions before. Regular expressions – regexes for short – are designed to let us perform fuzzy searches inside strings. For example, we know that "cat".contains("at") is true but what if we wanted to match any three-letter word that ends in “at”?

This is what regexes are designed to solve, although they use slightly clumsy syntax thanks to their Objective-C roots.

First you define the string you want to check:

let testString = "hat"

Next you create an NSRange instance that represents the full length of the string:

let range = NSRange(location: 0, length: testString.utf16.count)

That uses the utf16 count to avoid problems with emoji and similar.

Next you create an NSRegularExpression instance using some regex syntax:

let regex = try! NSRegularExpression(pattern: "[a-z]at")

[a-z] is regex’s way of specifying any letter from “a” through “z”. This is a throwing initializer because you might attempt to provide an invalid regular expression, but here we have...

]]>
How to upgrade to modern app infrastructure https://www.hackingwithswift.com/articles/107/how-to-upgrade-to-modern-app-infrastructure https://www.hackingwithswift.com/articles/107/how-to-upgrade-to-modern-app-infrastructure Add tests, use CocoaPods, get continuous integration, and more! Mon, 21 May 2018 09:22:26 +0000 It's easy to look at your project and think, "I could have done this better," but what does it take to really fix things? I wrote a series of articles showing exactly how to upgrade your projects for modern app infrastructure: getting great unit tests where you had none before, adopting smart coding conventions to make your work easier to read, streamlining tedious work using Fastlane, and more.

These articles all build upon the same example project from GitHub, but you can apply their principles anywhere else. If you're using my project then you should follow the articles sequentially, but if you just want to upgrade your own projects then you can read whichever articles you like – just skip to the part that interests you.

Here are direct links to the various parts:

  1. How to refactor your code to add tests
  2. How to add CocoaPods to your project
  3. How to clean up your code formatting with SwiftLint
  4. How to streamline your development with Fastlane
  5. How to save and share your work with GitHub
  6. How to validate code changes using CircleCI
]]>
10 Quick Swift Tips https://www.hackingwithswift.com/articles/106/10-quick-swift-tips https://www.hackingwithswift.com/articles/106/10-quick-swift-tips Try out something new with these tips and tricks Sun, 20 May 2018 22:36:50 +0000 Swift is a huge language with lots of interesting syntax, features, and quirks to take advantage of if you know they exist. In this article I want to walk you through ten of them quickly, including hands-on code examples so you can try them immediately.

1. Existentials of classes and protocols

An “existential type” allows us to say what kind of functionality we want a type to have rather than requesting something specific. So, you should already know that you can we can write functions that accept a class or a subclass:

func process(user: User) { }

And we can write functions that accept any kind of object as long as it conforms to a protocol:

func identify(thing: Identifiable) { }

Swift allows us to represent existentials of classes and protocols at the same time.

As an example, here’s a protocol and a class that conforms to the protocol:

protocol CanCook { }
class CelebrityChef: CanCook { }

And here’s a class along with a subclass of it:

class Appliance { }
class Hairdryer: Appliance { }

So, we have a protocol defining things that can cook, and a class that defines things we have in our home. Things become more complex when we want to combine the two – to work with appliances that can cook food.

Defining them in easy enough, because they can subclass from Appliance and conform to CanCook, like this:

class Oven: Appliance, CanCook { }
class Microwave: Appliance, CanCook { }

However using them is where Swift’s existential support comes in. Unless you’re best friends with Mary Berry, it’s unlikely you’ll get a celebrity chef to come to your house to cook a meal. Similarly, unless you’re desperate it’s unlikely you’ll try to cook your dinner with a hairdryer.

As a result, both of these two functions aren’t good enough – they don’t fully describe the types of data we want to accept:

func makeDinner(using: Appliance) { }
func makeDinner(using: CanCook) { }

Fortunately, Swift lets ...

]]>
Build a unit converter for watchOS https://www.hackingwithswift.com/articles/105/build-a-unit-converter-for-watchos https://www.hackingwithswift.com/articles/105/build-a-unit-converter-for-watchos Use WatchKit and Swift to find out how many inches are in a parsec Sat, 19 May 2018 22:47:17 +0000 Part 2 in a series of cross-platform Swift apps. You can read these in any order you want – each article builds the same app on a different platform, but all are standalone tutorials too.

  1. Build a unit converter for macOS
  2. Build a unit converter for watchOS
  3. Build a unit converter for tvOS

watchOS comes from the same foundations as iOS and macOS, both literally (it uses Apple’s Foundation framework) and figuratively. However, it has one fundamental and inescapable difference: it must run on a comparatively tiny screen, and it must function efficiently enough to satisfy extraordinarily short attention spans.

I already wrote a whole book teaching how to make watchOS apps (yes, it’s fully updated for the latest version of Swift, and actually comes with lifetime updates for free!), but in this article I’m going to take a different approach to the book.

Rather than teach you watchOS programming from scratch, we’re just going to dive into a real-world project and see how we get on. This will mean you having to learn a variety of things at once (the book is paced more carefully), but on the flip side it will give you a pretty clear idea of whether watchOS programming is for you or not.

In this project we’re going to solve a classic introductory problem with a twist. One of the first things I ever developed was a Celsius to Fahrenheit converter (using Visual Basic, of all things!), and there are similar projects for a variety of other languages and platforms.

Here, though, we have Apple’s Foundation framework, so we’re going to take it up a notch: we’re going to build a general-purpose converter that can handle any distance, duration, mass, or temperature units. Ever wondered how many astronomical units there are in 10 yards? Or how many teaspoons of liquid fit into one gallon? Soon you’ll know!

This article is going to be particularly i...

]]>
Build a unit converter for macOS https://www.hackingwithswift.com/articles/104/build-a-unit-converter-for-macos https://www.hackingwithswift.com/articles/104/build-a-unit-converter-for-macos Use AppKit and Swift to find out how many inches are in a parsec Fri, 18 May 2018 18:07:42 +0000 Part 1 in a series of cross-platform Swift apps. You can read these in any order you want – each article builds the same app on a different platform, but all are standalone tutorials too.

  1. Build a unit converter for macOS
  2. Build a unit converter for watchOS
  3. Build a unit converter for tvOS

If you can build iOS apps, you can build macOS apps too. Not only does Swift provide a shared language, but the two platforms also share a huge range of frameworks – Core Graphics, Core Image, Core Animation, MapKit, WebKit, Auto Layout, and more all work almost identically on both iOS and macOS.

Of course, where the two differ is in their user interface frameworks: where iOS uses UIKit, macOS uses AppKit. This is a significantly older framework that has a number of quirks and curiosities that can sometimes trip up folks moving over from iOS, but for several years now Apple has been working to modernize it.

In short, even though AppKit is still quite different from UIKit, you’re likely to find just as many similarities than differences – there really has never been a better time to make a macOS app.

I already wrote a whole book teaching how to make macOS apps (yes, it’s fully updated for the latest version of Swift, and actually comes with lifetime updates for free!), but in this article I’m going to take a different approach to the book.

Rather than teach you macOS programming from scratch, we’re just going to dive into a real-world project and see how we get on. This will mean you having to learn a variety of things at once (the book is paced more carefully), but on the flip side it will give you a pretty clear idea of whether macOS programming is for you or not.

In this project we’re going to solve a classic introductory problem with a twist. One of the first things I ever developed was a Celsius to Fahrenheit converter (using Visual Basic, o...

]]>
Seven useful methods from CGRect https://www.hackingwithswift.com/articles/103/seven-useful-methods-from-cgrect https://www.hackingwithswift.com/articles/103/seven-useful-methods-from-cgrect Insetting, offsetting, transformation, and more! Thu, 17 May 2018 22:31:34 +0000 The humble CGRect struct might seem like a primitive beast, but it has a number of useful methods that let you adjust rectangles i a variety of ways.

Here are two simple CGRect instances we can work with:

let rect1 = CGRect(x: 20, y: 20, width: 100, height: 100)
let rect2 = CGRect(x: 50, y: 50, width: 100, height: 100)    

You can see that they overlap each other, and CGRect has three methods that let us evaluate that overlap. The first is the simplest: intersects() returns true if two rectangles overlap. In our case, this would be true:

rect1.intersects(rect2)

If you want more details, the intersection() method tells you where the intersection lies. Both our rectangles are 100 points wide, but the second one starts at X:50 and Y:50 so that’s where our overlap will begin. So, this code will return a new CGRect containing X:50 Y:50 width:70 height:70:

rect1.intersection(rect2)

The third option is the contains() method, which will return true if one rectangle entirely contains another. So, this will return false for us because the second rectangle lies partly outside the first:

rect1.contains(rect2)

There are four useful methods for transforming rectangles, but by far the most useful are insetBy() and offsetBy(). The former is used for expanding or contracting rectangles, and the latter for adjusting their positions.

For example, this will produce a rectangle at X:40 Y:40 width:60 height:60:

rect1.insetBy(dx: 20, dy: 20)

You’re specifying how much to grow or shrink the rectangle horizontally (dx) and vertically (dy) – these numbers apply to all four edges, which is why a horizontal change of 20 took our width from 100 to 60.

You can also make rectangles larger, like this:

rect1.insetBy(dx: -20, dy: -20)

I find negative insets helpful if you’re drawing behind something and want to make sure you have a fixed amount of margin on all edges.

As for offsetBy(), this is simply designed to move rectangles by whatev...

]]>
How to generate random numbers in Swift 4.2 and later https://www.hackingwithswift.com/articles/102/how-to-generate-random-numbers-in-swift https://www.hackingwithswift.com/articles/102/how-to-generate-random-numbers-in-swift Smart, simple, and secure new ways to generate randomness Wed, 16 May 2018 22:36:01 +0000 Swift 4.2 implements SE-0202: Random Unification, which introduces a new random API that’s native to Swift. This means you can for the most part stop using arc4random_uniform() and GameplayKit to get randomness, and instead rely on a cryptographically secure randomizer that’s baked right into the core of the language.

  • Note: At the time of writing SE-0202 is only available in the latest Swift 4.2 toolchain snapshots from https://swift.org/download.

Let’s dive in with one of the most common use cases for randomness: generating random numbers. This is done by calling the random() method on whatever numeric type you want, providing the range you want to work with. For example, this generates a random number in the range 1 through 4, inclusive on both sides:

let randomInt = Int.random(in: 1..<5)

Similar methods exist for Float, Double, and CGFloat:

let randomFloat = Float.random(in: 1..<10)
let randomDouble = Double.random(in: 1...100)
let randomCGFloat = CGFloat.random(in: 1...1000)

There’s even one for booleans, generating either true or false randomly:

let randomBool = Bool.random()

Checking a random boolean is effectively the same as checking Int.random(in: 0...1) == 1, but it expresses your intent more clearly.

Best of all, SE-0202 includes support for shuffling arrays. Previously I used GameplayKit for this, partly because it was easier than teaching newbies how to shuffle arrays well, and partly because GameplayKit has a number of advanced shuffling algorithms that let you shape your data.

However, GameplayKit’s shuffling implementation is imported really poorly into Swift: you need to typecast your Swift array to an NSArray then force-cast the result back to your original type, like this:

let numbers = [1, 2, 3]
let shuffledNumbers = (numbers as NSArray).shuffled() as! [Int]

This is something I have complained about *exte...

]]>
How to debug your view hierarchy using recursiveDescription https://www.hackingwithswift.com/articles/101/how-to-debug-your-view-hierarchy-using-recursivedescription https://www.hackingwithswift.com/articles/101/how-to-debug-your-view-hierarchy-using-recursivedescription Try this LLDB command to simplify your view debugging Tue, 15 May 2018 20:04:48 +0000 Xcode has a built-in view debugger that captures all the views inside the currently running app, then shows them in 3D. You can then filter that list based on classes, subclasses, and contents of your views, or right-click on a view and choose Focus On UIView to view just part of your view hierarchy.

But while this view debugger is great to have around, it can be clumsy to use in two situations: trying to compare multiple view frames at the same time, and trying to compare one view’s frames across several runs of your app.

Fortunately, UIView has a hidden method called recursiveDescription() that prints out an ASCII rendering of your view hierarchy – all the views, their children, their positions, some of their content, whether they are responding to user input, and so on.

This method is specifically there for debugging purposes – it’s not something you would ever want to call in production – but because it uses plain text in Xcode’s console, it can be easier to compare one view’s position against another, or perhaps against itself if you’re looking at different runs of your app.

Swift doesn’t make it easy to call hidden methods; the easiest way I’ve found is to run this from the LLDB prompt in Xcode:

po yourView.value(forKey: "recursiveDescription")!

So, place a breakpoint in your code wherever you’d like to inspect your view hierarchy, and try it out!

]]>
How to validate code changes using CircleCI https://www.hackingwithswift.com/articles/100/how-to-validate-code-changes-using-circleci https://www.hackingwithswift.com/articles/100/how-to-validate-code-changes-using-circleci Run your tests for every commit and pull request Sun, 13 May 2018 22:17:46 +0000 Part 6 in a series of tutorials on modern app infrastructure:

  1. How to refactor your code to add tests
  2. How to add CocoaPods to your project
  3. How to clean up your code formatting with SwiftLint
  4. How to streamline your development with Fastlane
  5. How to save and share your work with GitHub
  6. How to validate code changes using CircleCI


Continuous integration (CI for short) is the process of merging your code with a central repository on a regular basis, which might sound good but has pitfalls. For example, if you have multiple team members committing to your GitHub repository several times a day, what happens if someone breaks the master branch? Or what happens if someone writes code that causes a test to fail?

In this final installment of our mini-series on modern app infrastructure, I want to introduce you to automated testing using CircleCI. This is a company that hosts its own macOS servers running various Xcode builds, and can connect directly to your GitHub repository so that every time you make changes they will automatically run your full test suite to double check that all your changes are good.

Even better, as you’ll see you can even have CircleCI run its tests on pull requests to your repository, so that no one – not even you, if you want – can get code into the repository unless your tests pass. The result is that your team can commit code more often and with more confidence.

Now, I know what you’re thinking: CircleCI is a business and they need to make money, so how much does this ...

]]>
How to save and share your work with GitHub https://www.hackingwithswift.com/articles/99/how-to-save-and-share-your-work-with-github https://www.hackingwithswift.com/articles/99/how-to-save-and-share-your-work-with-github Keep your work safe with version control Sat, 12 May 2018 22:38:58 +0000 Part 5 in a series of tutorials on modern app infrastructure:

  1. How to refactor your code to add tests
  2. How to add CocoaPods to your project
  3. How to clean up your code formatting with SwiftLint
  4. How to streamline your development with Fastlane
  5. How to save and share your work with GitHub
  6. How to validate code changes using CircleCI


Although the term itself is relatively recent, open source software has been around since software has been around – teams in different universities used to just mail each other their source code.

These days, most developers store their source code on GitHub, and as a result it has become the largest repository of open-source work in existence – it hosts over 80 million repositories are stored there, with thousands more added every single day. Even better, if you’re happy releasing your code under an open source license that allows others to use your code, GitHub doesn’t cost a penny – it’s free!

In this fifth part of our series on modern app infrastructure we’re going to look at how to save our work to GitHub then share it with others. This process won’t take long, so afterwards I’m going to provide you with a useful primer of some other helpful source control commands because it’s such a useful skill for developers.

  • If you’d like to learn more about Git, I have a whole book about it and other useful topics that all coders should know: Beyond Code.

Why use version control?

GitHub is powered by Git, which is a *v...

]]>
How to streamline your development with Fastlane https://www.hackingwithswift.com/articles/98/how-to-streamline-your-development-with-fastlane https://www.hackingwithswift.com/articles/98/how-to-streamline-your-development-with-fastlane Run tests, take screenshots, send to the App Store, and more Fri, 11 May 2018 22:44:13 +0000 Part 4 in a series of tutorials on modern app infrastructure:

  1. How to refactor your code to add tests
  2. How to add CocoaPods to your project
  3. How to clean up your code formatting with SwiftLint
  4. How to streamline your development with Fastlane
  5. How to save and share your work with GitHub
  6. How to validate code changes using CircleCI


In the dark old days of app development you needed to build projects, fight with certificates and provisioning profiles, take screenshots across a multiple of devices, and more – all by hand, too.

Fortunately, these days we have Fastlane: a project with the specific aim of saving developer time by automating common tasks. It can take screenshots of your app in any devices you want and at any places you want, it can push new versions of your app out to beta testers or to the App Store, and it can even – gulp! – take most of the pain of provisioning profiles away.

To give you a quick tour around Fastlane, we’re going to upgrade our sample project to use it. If you’ve been following the other parts of this tutorial you should already have a working project ready to try out, but if you’re not you can try checking out our original example project from GitHub – there’s a good chance things won’t be quite the same here, though.

Warning: The example project has been written specifically for this tutorial series, and contains mistakes and problems that we’ll be examining over this tutorial series. If you’re looking f...

]]>
How to clean up your code formatting with SwiftLint https://www.hackingwithswift.com/articles/97/how-to-clean-up-your-code-formatting-with-swiftlint https://www.hackingwithswift.com/articles/97/how-to-clean-up-your-code-formatting-with-swiftlint Get consistent code the easy way Thu, 10 May 2018 22:51:55 +0000 Part 3 in a series of tutorials on modern app infrastructure:

  1. How to refactor your code to add tests
  2. How to add CocoaPods to your project
  3. How to clean up your code formatting with SwiftLint
  4. How to streamline your development with Fastlane
  5. How to save and share your work with GitHub
  6. How to validate code changes using CircleCI


There are lots of important and interesting discussions software developers can have: what architecture to use, how to split up your project into sensible components, and what CocoaPods can help you achieve your goals faster, for example.

But there are lots of discussions that aren’t interesting unless you enjoy empty arguments: tabs vs spaces, whether to use Array<Int> or [Int], and which of name: String, name : String, and name :String are correct.

You probably have an opinion on each of those and that’s fine, but does your opinion match those of the rest of your team? How about those of developers who came before you? The answer is “almost certainly not”, which is why we have linters – tools that inspect your code to make sure it matches whatever style guide you have agreed on in your team.

In the Swift world we have SwiftLint, created by serial Swift community contributor JP Simard and others. SwiftLint hooks into Apple’s own SourceKit framework to parse your Swift code, which means it supports the full range of Swift syntax and remains up to date as Swift continues to evolve.

Swift...

]]>
How to deliver a talk at a programming conference https://www.hackingwithswift.com/articles/96/how-to-deliver-a-talk-at-a-programming-conference https://www.hackingwithswift.com/articles/96/how-to-deliver-a-talk-at-a-programming-conference Get started with tips from conference veterans Tue, 08 May 2018 19:56:25 +0000 If you’ve ever wanted to try speaking at a conference, I’ve got good news for you: not only is it less scary than you might think, but it’s also a great way to learn more about the topic you teach while also helping contribute to our community.

I believe it’s important for our community to find and encourage new voices to come forward and talk about their experiences and ideas, so I’ve put together this article as a consolidated resource to new speakers get started.

In this article you’ll find:

  • Tips for locating good events where you can speak
  • How to write good proposals and titles
  • Examples of speaker bios from well-known folks in our industry
  • Advice for crafting great slides and delivering your talk

At the same time, I’m also just one person with one very specific background, so I also want to introduce you to a range of other views from folks who are acclaimed speakers in our community.

These people are just as keen to encourage new speakers to come forward, and I’m really grateful they took the time to contribute to this article – thank you to Craig Clayton, Kristina Fox, Ash Furrow, Cate Huston, Ben Scheirman, Ellen Shapiro, Daniel Steinberg, and John Sundell for contributing their time and suggestions!

Please keep in mind that there’s no one ideal route to delivering a great presentation – there are a range of suggestions here, and you need to do works best for you.

If you want to jump ahead to a specific point in the article, here’s your chance:

]]>
How to add CocoaPods to your project https://www.hackingwithswift.com/articles/95/how-to-add-cocoapods-to-your-project https://www.hackingwithswift.com/articles/95/how-to-add-cocoapods-to-your-project Import third-party modules the easy way Mon, 07 May 2018 22:03:44 +0000 Part 2 in a series of tutorials on modern app infrastructure:

  1. How to refactor your code to add tests
  2. How to add CocoaPods to your project
  3. How to clean up your code formatting with SwiftLint
  4. How to streamline your development with Fastlane
  5. How to save and share your work with GitHub
  6. How to validate code changes using CircleCI


CocoaPods is the world’s largest collection of pre-built, open source modules for iOS developers – some 46,000 at the time of writing.

Although it’s far from perfect (I have complained about it a great deal in the past), CocoaPods has done more to streamline developer productivity than any other piece of our infrastructure: you can literally pull incredible functionality into your app in just a few seconds, and keep it updated over time.

This is part two of a tutorial series about upgrading your apps to use modern infrastructure – tools that help you write better software by automating tasks. In this installment we’re going to look at another problem our test app has: although it uses SwiftyBeaver for logging, it does so by literally copying the files directly into the project. While this certainly works it means any future updates to SwiftyBeaver won’t automatically be merged into our app.

CocoaPods is designed to solve this. Rather than copying someone else’s code into your project, you reference their Git repository and a version number and let CocoaPods install it for you. Even better, you can upd...

]]>
How to refactor your app to add unit tests https://www.hackingwithswift.com/articles/94/how-to-refactor-your-app-to-add-unit-tests https://www.hackingwithswift.com/articles/94/how-to-refactor-your-app-to-add-unit-tests Take old, messy code and rearchitect it for the future Sun, 06 May 2018 22:50:26 +0000 Part 1 in a series of tutorials on modern app infrastructure:

  1. How to refactor your code to add tests
  2. How to add CocoaPods to your project
  3. How to clean up your code formatting with SwiftLint
  4. How to streamline your development with Fastlane
  5. How to save and share your work with GitHub
  6. How to validate code changes using CircleCI


Every developer has, at some point, written terrible code. It might have been because you were early in your career, it might have been because you didn’t know any better at the time, it be because you were under pressure and had to rush, or it might have been for any number of other reasons.

I’ve already written extensively about ways to fix massive view controllers (see here, here, and here), but in this tutorial series I want to focus on app infrastructure – tools that help you write better software by automating tasks.

To make things as realistic as possible, I built a Swift project that contains a number of problems that we’ll investigate here and across the following tutorials in this series.

Warning: This project has been written specifically for this tutorial series, and contains mistakes and problems that we’ll be examining over this tutorial series. If you’re looking for example code to learn from, this is the wrong place.

To get ...

]]>