Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to use an Objective-C category within Swift?

Tags:

I'm trying to import some category methods into my Swift file without any luck.

ios-Bridging-Header.h:

#import "UIColor+Hex.h"

UIColor+Hex.h

#import <UIKit/UIKit.h>

@interface UIColor (Hex)

+ (UIColor *)colorWithHex:(NSUInteger)hexInt;
+ (UIColor *)colorWithHexString:(NSString *)hexString;

@end

I would expect the autocomplete to reveal UIColor(hexInt: NSUInteger) and UIColor(hexString: String)

like image 266
sevenflow Avatar asked Jun 05 '14 15:06

sevenflow


People also ask

Can I use Objective-C in Swift?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

How can Swift and Objective-C be used in the same project?

To access and use swift classes or libraries in objective-c files start with an objective-c project that already contains some files. Add a new Swift file to the project. In the menu select File>New>File… then select Swift File, instead of Cocoa Touch Class. Name the file and hit create.

What is the use of category in Objective-C?

Categories provide the ability to add functionality to an object without subclassing or changing the actual object. A handy tool, they are often used to add methods to existing classes, such as NSString or your own custom objects.


2 Answers

Actually, your category is transtlated to Swift as follows:

extension UIColor {

    init(hex hexInt: Int) -> UIColor

    init(hexString: String) -> UIColor

}

And because of that, you should be using:

let color = UIColor(hex: 0xffffff) // instead of hexInt:

let color = UIColor(hexString: "ffffff")

Autocompletion may still be buggy in the beta software, though.

like image 84
akashivskyy Avatar answered Oct 31 '22 07:10

akashivskyy


You can use Objective-C categories directly in Swift. This gets really interesting for some of the bridged classes, like String. Extend NSString with a category in Objective-C, and then you can access it from Swift (directly on String!)

The way to do this is by creating a "bridging header" in your Swift project.

Full instructions here.

The short of it is:

  1. Make a .h header file (in Objective-C) with all the other #import statements in it
  2. Put the path to that file in Objective-C Bridging Header in your Build Settings
  3. No need to import the bridging header in your Swift file. It's already there
like image 25
Dan Rosenstark Avatar answered Oct 31 '22 09:10

Dan Rosenstark