Swift version: 5.6
Sometimes it’s important to add warnings and even errors to your code. For example, you might want to mark code as needing to be fixed, or mark placeholder values that must be filled in by whoever is using your code.
Swift has compiler directives that help us mark such issues in our code: #warning
and #error
. The former will force Xcode to issue a warning when building your code, and the latter will issue a compile error so your code won’t build at all.
Both of these work in the same way: #warning("Some message")
and #error("Some message")
. For example:
func encrypt(_ string: String, with password: String) -> String {
#warning("This is bad method of encryption")
return password + String(string.reversed()) + password
}
struct Configuration {
var apiKey: String {
// if you uncomment the below it will stop your code from building
// #error("Please add your API key below then delete this line.")
return "Enter your API key here"
}
}
Both #warning
and #error
work alongside the existing #if
compiler directive, only being triggered if the condition being evaluated is true. For example:
#if os(macOS)
#error("MyLibrary is not supported on macOS.")
#endif
Both #warning
and #error
are useful for different reasons:
#warning
is mainly useful as a reminder to yourself or others that some work is incomplete. Xcode templates often use #warning
to mark method stubs that you should replace with your own code. Think of #warning
as being like a FIXME
comment that automatically shows up in your build output.#error
is mainly useful if you ship a library that requires other developers to provide some data. For example, an authentication key for a web API – you want users to include their own key, so using #error
will force them to change that code before continuing.SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.