How to create a Swift object in Objective-C?

后端 未结 3 2031
时光说笑
时光说笑 2021-01-06 05:32

If you define a swift class like this

@objc class Cat {

}

In swift you can just do

var c = Cat()

But how

相关标签:
3条回答
  • 2021-01-06 06:15

    The most direct way is to subclass Cat from NSObject. If you can't do that, you will need to make a class method or a function that returns a Cat.

    @objc class Cat {
        class func create() -> Cat {
            return Cat()
        }
    }
    func CreateCat() -> Cat {
        return Cat()
    }
    
    
    Cat *cat = [Cat create];
    Cat *cat = CreateCat();
    
    0 讨论(0)
  • 2021-01-06 06:20

    You can declare +alloc in a dummy category (don't need to implement it):

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

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

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

    all without needing to change the Swift code.

    0 讨论(0)
  • 2021-01-06 06:25

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

    Swift:

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

    Obj-c:

    Cat *cat = Cat.create;
    
    0 讨论(0)
提交回复
热议问题