Inherit from a Swift class in Objective C OC继承Swift类)

Inherit from a Swift class in Objective C OC继承Swift类)

七月 15, 2020
小时光

搜到的相关资料基本来自这个帖子**Inherit from a Swift class in Objective C **。事实上一楼回复已经说的很明确了,Objective-C不能继承Swift类。

Unfortunately, it’s not possible to subclass a Swift class in Objective-C. Straight from the docs:

那么换个思路,为什么一定要用继承呢?用category可以吗?经过我的测试是可以的,代码如下:

Swift文件

1
2
3
4
5
import UIKit

@objcMembers open class TestModel: NSObject {
var testName: String = String()
}

OC的.h文件

1
2
3
4
5
6
7
8
9
#import <Foundation/Foundation.h>
// 桥接文件
#import "****-Swift.h"


@interface TestModel (Add)
- (void)configTestName;
@end

OC的.m文件

1
2
3
4
5
6
7
8
9
#import "TestModel+Add.h"

@implementation TestModel (Add)

- (void)configTestName {
self.testName = @"12323";
}

@end