rickdecard
rickdecard

Reputation: 211

UIInterpolatingMotionEffect swift XCode

I am trying to define a motion effect with the code in the new language Swift

var axis_x_motion: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect( "center.x", UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis)

but Xcode returns the error: "Use of unresolved identifier 'UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis'"

Also I am trying with

var axis_x_motion: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect( "center.x", TiltAlongHorizontalAxis)

but Xcode then returns the error: "Use of unresolved identifier 'TiltAlongHorizontalAxis'"

Upvotes: 0

Views: 914

Answers (2)

Tom Hancocks
Tom Hancocks

Reputation: 440

Before I go in to an explanation, lets take a look at the corrected code

var axisXMotion = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)

As a quick bit of information, the convention of the Swift language is to be using CamelCase rather than snake_case.

Right, on to what these changes mean. Swift uses a concept of named arguments and will require that you use those argument names in most situations. For instance if we take a look at the initialiser for UIInterpolatingMotionEffect we can see that it requires two arguments,

init(keyPath: String!, type: UIInterpolatingMotionEffectType)

These arguments are named keyPath and type, so we need to specify them in our call.

As for the unrecognised identifiers, this comes down to how Swift identifies enumeration values. In C we were able to provide the name of the identifier in such a way that we could say UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis. However in Swift we need to provide both the name and the case of the enumeration, like so:

UIInterpolatingMotionEffectType.TiltAlongHorizontalAxis

But as you can see I didn't specify the UIInterpolatingMotionEffectType portion of that previously. This is because Swift uses Type Inference. The compiler can see that the argument is expected to be of type UIInterpolatingMotionEffectType and thus allows us to omit it and just specify .TiltAlongHorizontalAxis.

You can also make use of this Type Inference when creating your variable. The compiler knows that the initialiser of UIInterpolatingMotionEffect will return an object of type UIInterpolatingMotionEffect and so can infer the required type, thus allowing you to omit it.

I hope this helps explain some of this, and if you need any more help or explanation, just ask!

Upvotes: 3

Dash
Dash

Reputation: 17428

Swift uses a new dot-syntax for accessing enum values. You must combine the enum name (UIInterpolatingMotionEffectType) and the particular member value you wish to access (TiltAlongVerticalAxis) like this:

var axis_x_motion: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect("center.x", UIInterpolatingMotionEffectType.TiltAlongVerticalAxis)

Upvotes: 0

Related Questions