I know Swift is relatively new, but I was wondering if there was a way to determine the device type?
(Like you used to be able to do with a #define
)?
Mainly I would like to know how to differentiate OS X or iOS. I have found nothing on the subject.
To detect current device with iOS/Swift we can use UserInterfaceIdiom. It is an enum in swift, which tells which device is being used. The interface idiom provides multiple values in it's enum which are. When we run the above code on an iPhone device following is the result produced.
Open the Settings app to check your iOS information: Tap General. Tap About. It will show the device info, including the device name.
Go to your iPad or iPhone's home screen, then touch the "Settings" icon. From there, select "General." Next, tap "About." You'll see all of the information about your device, including the version of your iOS device.
When we talk about the device make, we refer to the Phone manufacturer (e.g. Apple, Samsung, Nokia and so on) and device model is generally the specific product such as iPhone, iPad/TAB etc. Any mobile devices will be categorized using make and model only.
If you're building for both iOS and macOS (and maybe for watchOS and tvOS, too), you're compiling at least twice: once for each platform. If you want different code to execute on each platform, you want a build-time conditional, not a run-time check.
Swift has no preprocessor, but it does have conditional build directives — and for the most part, they look like the C equivalent.
#if os(iOS) || os(watchOS) || os(tvOS) let color = UIColor.red #elseif os(macOS) let color = NSColor.red #else println("OMG, it's that mythical new Apple product!!!") #endif
You can also use build configurations to test for architecture (x86_64
, arm
, arm64
, i386
), Target environment (iOS simulator or Mac Catalyst), or -D
compiler flags (including the DEBUG
flag defined by the standard Xcode templates). Don’t assume that these things go together — Apple has announced macOS on arm64 to ship in 2020, so arm64 doesn’t imply iOS, and iOS Simulator doesn’t imply x86, etc.
See Compiler Control statements in The Swift Programming Language.
(If you want to distinguish which kind of iOS device you're on at runtime, use the UIDevice
class just like you would from ObjC. It's typically more useful and safe to look at the device attributes that are important to you rather than a device name or idiom — e.g. use traits and size classes to lay out your UI, check Metal for the GPU capabilities you require, etc.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With