1. Swift调用OC代码
@interface LSPerson : NSObject
@property (nonatomic, assign) int age;
@property (nonatomic, strong) NSString *name;
- (instancetype)initWithAge:(int)age name:(NSString*)name;
@end
- 首次创建OC代码时,会自动创建
OC-Bridging-Header.h
文件,这个文件主要用于声明Swift
中要用到的OC文件
// OC-Bridging-Header.h
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "LSPerson.h"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let person: LSPerson = LSPerson(age: 10, name: "carrot");
person.age = 20
print(person.age) // 输出:20
print(person.name) // 输出:carrot
}
}
2. OC调用Swift代码
- 需要被OC调用的Swift代码有两个条件:①继承自
NSObject
②使用@objcMembers
将成员和方法暴露出去
@objcMembers class Car: NSObject {
var price = 100.5
var owner = "lsp"
init(price: Double, owner: String) {
self.price = price
self.owner = owner
}
}
- 在需要调用Swift的OC代码处引入
#import "OC-Swift.h"
,这个文件默认存在
#import "LSPerson.h"
#import "OC-Swift.h"
@implementation LSPerson
-(void)callSwiftClass {
Car *car = [[Car alloc] initWithPrice:300.5 owner:@"carrot"];
NSLog(@"%@ %f %@",car, car.price, car.owner); // 输出:<OC.Car: 0x600001031b00> 300.500000 carrot
}
@end
3. Swift 中字符串的基本用法
image.png
4. String 和 Substring 的关系
image.png
网友评论