Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Swift Cookbook

You're reading from   Swift Cookbook Over 50 hands-on recipes to help you create apps, solve problems, and build your portfolio of projects in Swift

Arrow left icon
Product type Paperback
Published in Apr 2015
Publisher
ISBN-13 9781784391379
Length 392 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Table of Contents (13) Chapters Close

Preface 1. Getting Started with Xcode and Swift FREE CHAPTER 2. Standard Library and Collections 3. Using Structs and Generics 4. Design Patterns with Swift 5. Multitasking 6. Playground 7. Swift Debugging with Xcode 8. Integrating with Objective-C 9. Dealing with Other Languages 10. Data Access 11. Miscellaneous Index

Creating conditional code

Usually when we are developing, we have some cases where we would like to have different pieces of code according to our needs. For example, let's imagine that we would like to compare the performance of some functions written by us with some equivalent functions that were created on a third-party library. In this case, we can create some macros for using only our functions or for using only the third-party functions, allowing us to have the same application working in two different ways.

In this recipe, we will show how to create a log according to a platform and we can also enable or disable it if the execution is being affected by the excess of logs.

Getting ready

Create a new project called Chapter 1 Conditional Code, as shown earlier, and let's code a little bit.

How to do it...

To create a conditional code, follow these steps:

  1. After creating a new project, let's create a new file by navigating to File | New | File.... Now, choose Swift File and name it CustomLog.swift.

    Tip

    Don't save your files on a different folder from the project; this will give you problems in the future.

  2. Now, add the following code:
    func printLog(message: NSString){
        #if VERBOSE_LOG
            #if os(OSX)
                let OS="OS X"
            #else
                let OS="iOS"
            #endif
            
            #if arch(arm) || arch(arm64)
                let devicetype = "Mobile device"
            #elseif arch(x86_64) || arch(i386)
                let devicetype = "Computer"
            #else
                let devicetype = "Unkown"
            #endif
            
            NSLog("%@ on a %@ - %@", OS, devicetype, message)
        #endif
    }
  3. Now, go to the viewDidLoad method of your view controller, and add a call for this function, like this:
    printLog("Hello World")
  4. Try pressing play now; what do you see? The answer is—nothing! The reason is that the compiler knows nothing about the macro VERBOSE_LOG, which means that this macro is interpreted as false and the only thing that is created is an empty function.
  5. Now, go back to your project build settings, search for other swift flags, and add -DVERBOSE_LOG, as shown in the following screenshot:
    How to do it...
  6. Click on play again and you will see the log message.

How it works...

Currently, the Swift compiler has two defined macros: os() and arch(). The first one can receive OSX or iOS as argument, and the second one can receive x86_64, arm, arm64 and i386. Both macros will return a Boolean value. You can also create your own macro, defining it on your build settings.

The block that is evaluated as true will be compiled, and the other blocks will not be compiled; this way you can have code that calls OS-specific functions.

I would like to emphasize, mainly for those developers who are used to working with C projects, that the Apple documentation leaves a very clear message that Swift has no preprocessor; it only uses a trick on compilation time, so you can't use macros as we used to do on C or even on Objective-C. The only thing you can do is watch to see whether they are set or not.

There's more...

If you need, you can use the operators &&, ||, and ! as shown here: #if arch(arm64) && os(iOS), but you can't use any kind of comparator operator such as ==, <, and so on.

If you are interested in knowing more options that you can add to other Swift flags, check out the Compiling from the command line recipe in this chapter.

You have been reading a chapter from
Swift Cookbook
Published in: Apr 2015
Publisher:
ISBN-13: 9781784391379
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image