Swift

Swift Day18 OC 和 Swift 混编

2020-12-22  本文已影响0人  望穿秋水小作坊
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-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代码
@objcMembers class Car: NSObject {
    var price = 100.5
    var owner = "lsp"
    init(price: Double, owner: String) {
        self.price = price
        self.owner = owner
    }
}
#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
上一篇下一篇

猜你喜欢

热点阅读