0

I have been using Objective-C for years and I am now making my first steps using Swift.

In my existing projects I have been using quite a few different macros like

#define IS_IPAD      ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
#define IS_IPHONE    ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)

Since Swift does not support such macros Apple recommends to use functions and generics instead. This is also the solution which is recommended in other threads (e.g. here).

So I could simply create some Tools class and add the macros as methods to it:

class Tools {
    static func IS_IPAD() -> Bool {
        return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
    }
}

class OtherClass {
    func doSomething() {
        if (Tools.IS_IPAD())
            ...
    }
}

However, the examples I have found seem to use functions without any class, like in the thread linked above:

func FLOG(message:String, method:String = __FUNCTION__) {
    println("\(method): \(message)")
}

FLOG("Illegal value: \(value)")

Since I am new to Swift I wonder if this is only to keep the examples short or if it is possible to define and use such macro like function without a class.

Chirag Kothiya
  • 955
  • 5
  • 12
  • 28
Andrei Herford
  • 17,570
  • 19
  • 91
  • 225
  • 1
    Create a new swift project -> write a function outside any class -> compile it. Does it compile? – Sweeper Jun 17 '19 at 14:07

2 Answers2

2

You can create global computed properties to achieve something like that.

Example:

var isIPad: Bool {
    return UIDevice.current.userInterfaceIdiom == .pad
}

var isIPhone: Bool {
    return UIDevice.current.userInterfaceIdiom == .phone
}

You can use it like:

class OtherClass {
    func doSomething() {
        if isIPad {
            print("It is an iPad")
        } else if isIPhone {
            print("It is an iPhone")
        }
    }
}
PGDev
  • 23,751
  • 6
  • 34
  • 88
1

You can indeed use global functions, but then you have the potential for name collisions. As an app grows and evolves you might add third party frameworks, include code from other teams, etc. If anybody uses the same global function name then you have a problem.

Making the functions static functions of a class solves this by "namespacing" those functions (It puts them in the namespace of their owning class.)

For sample code it's simpler to just use global functions, but for real-world applications class functions are probably a better choice.

Duncan C
  • 128,072
  • 22
  • 173
  • 272