Avatar ·

Determining device type (iPhone/iPad) in Swift: UI_USER_INTERFACE_IDIOM() and alternatives

Hello everyone! I just started learning Swift and encountered a problem when determining the device type (iPhone or iPad). In old Objective-C projects, I saw the UI_USER_INTERFACE_IDIOM() macro, but it doesn't work directly in Swift.

\n\n

I need to write code that behaves differently on iPad and iPhone. For example, on iPad I want to show a controller as UISplitViewController, and on iPhone as a regular UINavigationController.

\n\n

Here's what I tried, but it doesn't compile:

\n\n
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad {\n    // iPad\n} else {\n    // iPhone\n}\n
\n\n

Xcode gives an error: "Use of unresolved identifier 'UI_USER_INTERFACE_IDIOM'". How to correctly determine the device type