iOS假装进步swift学习iOS开发

Swift5.1 - oc到swift过渡

2019-08-29  本文已影响28人  HChase

条件编译

#if os(macOS) || os(iOS)
// 操作系统

#elseif arch(x86_64) || arch(arm64)
// 架构

#elseif swift(<3) || swift(>=5)
// swift版本号

#elseif targetEnvironment(simulator)
// 模拟器

#elseif canImport(Foundation)
// 是否能导入某个模块

#else

#endif

系统版本号检查

if #available(iOS 13, macOS 10.12, *) {
    // .....
}

MARK、TODO、FIXME

swift调用oc

oc调用swift


swift文件中定义:

@objcMembers class Cat: NSObject {
    var age: Int
    var name: String
    
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
    
    func eat() {
        print("cat eat")
    }
}

oc文件中调用:

#import "ocToSwift-Swift.h"

void test() {
    Cat *cat = [[Cat alloc] initWithAge:10 name:@"xiaohei"];
    [cat eat];
}

@objc(BYCat)
@objcMembers class Cat: NSObject {
    var age: Int
    
    @objc(color)
    var name: String
    
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
    
    func eat() {
        print("cat eat")
    }
}

oc文件中调用:

#import "ocToSwift-Swift.h"

void test1() {
    BYCat *cat = [[BYCat alloc] initWithAge:20 name:@"白色"];
    cat.color = @"黑色";
}

选择器

@objcMembers class Cat: NSObject {
    func test1() { print("test1") }
    func test2() { print("test2") }
    func test() {
        perform(#selector(test1))
    }
}
上一篇下一篇

猜你喜欢

热点阅读