Swift snippet #12 โ€” Using standard library names for your types

John Sundell
Swift Snippets ๐Ÿš€
1 min readMar 28, 2017

--

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.

--

--

John Sundell
Swift Snippets ๐Ÿš€

Find my weekly Swift articles on swiftbysundell.com. Iโ€™m no longer publishing on Medium.