How do I create a Swift object in Objective-C?

If you have defined a swift class like

@objc class Cat {

}

      

In fast mode, you can simply do

var c = Cat()

      

But how do you make an instance Cat

in Objective-C?

Subclassing NSObject

works because you can "alloc-init", but can we achieve this without subclassing the Objective-C class?

+3


source to share


3 answers


The most direct way is to subclass Cat

from NSObject

. If you cannot do this, you will need to create a class method or function that returns Cat

.



@objc class Cat {
    class func create() -> Cat {
        return Cat()
    }
}
func CreateCat() -> Cat {
    return Cat()
}


Cat *cat = [Cat create];
Cat *cat = CreateCat();

      

+2


source


In modern objective-c, you can call functions like properties:

Swift:

class func create() -> Cat {
    return Cat()
}

      



Obj-C:

Cat *cat = Cat.create;

      

+1


source


You can declare +alloc

in a dummy category (no need to implement it):

@interface Cat (Alloc)
+ (instancetype)alloc;
@end

      

and then you can use normal alloc-init on it:

Cat *cat = [[Cat alloc] init];

      

without having to change Swift code.

0


source







All Articles