Siriss Siriss - 1 year ago 45
Swift Question

Declare property only on iOS

I am making a SpriteKit game for iOS, OSX, and tvOS. I am trying to use the accelerometer for my iOS target. I have the check for iOS on import of the CMMotionManager, but I can't seem to get the check to work when creating my motion manager property.

#if os(iOS)
import CMMotionManager

class MainPlayScene: TCScene, SKPhysicsContactDelegate {

//MARK: Properties
@available(iOS 9, *) // Does not work, just trying things out....
var motionManager:CMMotionManager {
return motionManager

How can I do this check?

EDIT: It is late here, and the more I think about it, correct me if I am on the wrong track all together. How can I use the accelerometer for iOS only and still share my scene code?

Answer Source

You use the same syntax that you used for your import statement. This is also what apple does in their sample game DemoBots.

#if os(iOS)
var motionManager....

#if os(tvOS)

You can also do multiple checks and use else/else if

 #if os(iOS) || os(tvOS)
 #elseif os(OSX)
 ... // Code for other platforms

How to determine device type from Swift? (OS X or iOS)

Just curious, any particular reason you make the motionManager property computed?