1. Swift調(diào)用OC代碼
- 創(chuàng)建OC下的
LSPerson
類
@interface LSPerson : NSObject
@property (nonatomic, assign) int age;
@property (nonatomic, strong) NSString *name;
- (instancetype)initWithAge:(int)age name:(NSString*)name;
@end
- 首次創(chuàng)建OC代碼時葵蒂,會自動創(chuàng)建
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調(diào)用Swift代碼
- 需要被OC調(diào)用的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
}
}
- 在需要調(diào)用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 中字符串的基本用法
4. String 和 Substring 的關(guān)系