-1

I'm following an Objective-C tutorial on how to animate a menu with UIKit Dynamics and I'm having some trouble translating the following code from Objective-C to Swift.

animator.h

@interface Animator : NSObject

+ (instancetype)animatorWithScreen:(UIScreen *)screen;

- (void)addAnimation:(id<Animation>)animatable;
- (void)removeAnimation:(id<Animation>)animatable;

@end

@interface UIView (AnimatorAdditions)

- (Animator *)animator;

@end

animator.m

@implementation Animator
{
}

+ (instancetype)animatorWithScreen:(UIScreen *)screen
{
    if (!screen) {      
        screen = [UIScreen mainScreen];
    }
    Animator *driver = objc_getAssociatedObject(screen, &ScreenAnimationDriverKey);
    if (!driver) {
        driver = [[self alloc] initWithScreen:screen];
        objc_setAssociatedObject(screen, &ScreenAnimationDriverKey, driver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return driver;
}

@implementation UIView (AnimatorAdditions)

- (Animator *)animator
{
    return [Animator animatorWithScreen:self.window.screen];
}

@end

I was able to get everything else working, but I'm unsure how to get the UIView to have the animator property using Swift and also how to properly translate:

objc_setAssociatedObject(screen, &ScreenAnimationDriverKey, driver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
luk2302
  • 55,258
  • 23
  • 97
  • 137
Rui Gomes
  • 332
  • 1
  • 3
  • 16
  • 1
    regarding objc_setAssociatedObject: http://stackoverflow.com/questions/24133058/is-there-a-way-to-set-associated-objects-in-swift - regarding the animator: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html – luk2302 Jun 28 '15 at 19:05
  • Awesome, I'm not sure why I'm getting so heavily downvoted since I just wanted some guidelines. If you could add that as an answer I'll set it as the right one. – Rui Gomes Jun 28 '15 at 19:06

1 Answers1

1

There is already an existing discussion about objc_setAssociatedObject for swift: "Is there a way to set associated objects in Swift?".

What you are trying to do with the Animator is called an extension. That of course is available for swift as well - take a look at the docs for how to create one yourself.

Community
  • 1
  • 1
luk2302
  • 55,258
  • 23
  • 97
  • 137