Swift: #warning equivalent

前端 未结 14 1645
無奈伤痛
無奈伤痛 2020-11-28 18:52

Does Swift have a #warning equivalent? It\'s simply used to show a warning in Xcode\'s own GUI

I\'m also interested in whether there\'s a #error equivalent.

14条回答
  •  清歌不尽
    2020-11-28 19:22

    Post WWDC 2018 Update

    Starting with Xcode 10 and Swift 4.2 you will now be able to use #warning again like so:

    #warning("TODO: Clean up this code after testing")
    

    This will show up as a warning in Xcode just as expected!

    This works even in combination with #if checks, for example the following will only show a warning if your target platform is iOS:

    #if os(iOS)
        #warning("this code is untested in iOS")
    #endif
    

    There's also #error if you want your build to fail.


    Pre WWDC 2018 Answer

    In Swift using XCode 6 you can use different kinds of landmarks for different purposes. Here's what Apple says about it:

    Xcode now supports //MARK:, //TODO: and //FIXME: landmarks to annotate your code and lists them in the jump bar.

    So for setting a warning with a description you would use something like this:

    //TODO: Clean up this code after testing

    If you just want to set a short mark (assuming you will remember what to do), use this:

    //FIXME

    EDIT: These landmarks however only appear in the jump bar of XCode which might not be what you wish for and what one would expect – especially from the //TODO: and //FIXME marks. I've filed a radar on that: #17776817. Hopefully Apple will add this in the coming builds in XCode 6.

    SOLUTION (EDIT 2): If you install the Swift Linter via Homebrew (run brew install swiftlint after a brew update) and add the suggested build script to your project, then you will see all your TODO and FIXME landmarks appear as warnings within Xcode. SwiftLint will even add some more warnings/errors that you can configure to fit your needs – I can only recommend using SwiftLint and it solves this problem in a great way!

提交回复
热议问题