Swift snippet #12 — Using standard library names for your types

Tuesday, 28th March, 2017

You can find its Gist here!

Sometimes the most appropriate name for a nested type is a name that is already taken by the Swift standard library. At first, it may seem impossible to use these names, since you’ll get errors like this:

Circular enum raw types Error 😓

But the good news is that you can just add Swift. to disambiguate between your type and the standard library type!

Using the above snippet, you can now simply reference Error whenever you want to throw an error within Command 🚀, like this:

struct Command {
private let string: String
init(string: String?) throws {
guard let string = string else {
throw Error.missing
}
guard string.isValidCommand else {
throw Error.invalid(string)
}
self.string = string
}
}

This post is a guest post for the Swift-Snippets publication, which you can find out more about here. I also post weekly blog posts about Swift development which you can find here. You can also find me on Twitter @johnsundell.

--

--

--

It’s an initiative to share snippets that leverages the great power of Swift 🤘

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
John Sundell

John Sundell

Find my weekly Swift articles on swiftbysundell.com. I’m no longer publishing on Medium.

More from Medium

How to Write Images to Camera Roll in iOS

How to Write Images to Camera Roll in iOS

Introduction to Swift UI

Learning Swift

Every iOS developer should know these Xcode tricks