Swift 调用 Objective-C 类方法教程
在 Swift 中调用 Objective-C 的类方法,需要先导入 OC 的头文件,然后通过类名直接调用类方法。以下是示例代码:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 调用 OC 的类方法
let result = Calculator.add(10, b: 20)
print('10 + 20 = (result)')
}
}
其中,Calculator 是 OC 中的一个类,包含一个 add 类方法:
@interface Calculator : NSObject
+ (NSInteger)add:(NSInteger)a b:(NSInteger)b;
@end
@implementation Calculator
+ (NSInteger)add:(NSInteger)a b:(NSInteger)b {
return a + b;
}
@end
在 Swift 中,可以直接通过类名调用 OC 的类方法 Calculator.add(10, b: 20),并且可以使用返回值进行其他操作。
原文地址: https://www.cveoy.top/t/topic/oWmz 著作权归作者所有。请勿转载和采集!