After looking at all the answers this is what I ended up doing:
extension UIDevice {
static var isIphoneX: Bool {
var modelIdentifier = ""
if isSimulator {
modelIdentifier = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? ""
} else {
var size = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: size)
sysctlbyname("hw.machine", &machine, &size, nil, 0)
modelIdentifier = String(cString: machine)
}
return modelIdentifier == "iPhone10,3" || modelIdentifier == "iPhone10,6"
}
static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
}
if UIDevice.isIphoneX {
// is iPhoneX
} else {
// is not iPhoneX
}
Pre Swift 4.1 you can check if the app is running on a simulator like so:
TARGET_OS_SIMULATOR != 0
From Swift 4.1 and onwards you can check if the app is running on a simulator using the Target environment platform condition:
#if targetEnvironment(simulator)
return true
#else
return false
#endif
(the older method will still work, but this new method is more future proof)