NEW: Nominations are now open for the 2019 Swift Community Awards! >>

How to add warnings and errors to your code using #warning and #error

Swift version: 5.1

Paul Hudson    @twostraws   

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.

LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!

Available from iOS 8.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5