0

Is it possible to use Swift extensions in Obj-C?

I'm extending the UIView class with some fade animation like this:

import Foundation
import UIKit

extension UIView {
    func fadeOut(duration: NSTimeInterval) {
        UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            self.alpha = 0.0
            }, completion: nil)
    }
}

I unsuccessfully tried to call it in my Obj-C class like

[someView fadeOut(1.0)]
user3607973
  • 345
  • 1
  • 5
  • 15
  • Did it give you a compiler error or a runtime error? what error does it give? Try replacing `UIView.animateWithDuration` with `self.animateWithDuration` where self is referring to the UIView which you are expanding upon – milo526 Apr 18 '15 at 20:32

1 Answers1

4
func fadeOut(duration: NSTimeInterval)

maps to Objective-C as

- (void)fadeOut:(NSTimeInterval)duration;

and is therefore called as

[someView fadeOut:1.0];
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    Duh! Using both languages at once is messing with my head. – user3607973 Apr 18 '15 at 20:37
  • I can't seem to get this to work (where I dragged a Swift extension into an objective-c project). Do you need to import the extension into the objective-c class that uses it, and if so, what is the correct syntax? – rdelmar May 21 '15 at 18:31
  • @rdelmar: Did you `#import "<#YourProjectName#>-Swift.h"` in the Objective-C file? Compare "Importing Swift into Objective-C" in https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html or "Using Swift Classes in Objective-C" in http://stackoverflow.com/a/24005242/1187415. – Martin R May 21 '15 at 18:37
  • I thought I had tried that one, but I guess I didn't. Thanks, that worked. – rdelmar May 21 '15 at 18:42