Update: 2022/04/17
一. Swift混编相关
(1) Swift调用OC, 借助桥接文件
1.手动生成 命名格式 <target>-Bridging-Header.h 的文件
2.把需要引入Swift的头文件添加到桥接文件
(2) OC调用Swift, Xcode默认生成头文件命名格式: <target>-Swift.h
1.导入默认生成的头文件
2.暴露的Swift类, 需要继承 NSObject
3.使用@objc 标记需要暴露的成员; 另外@objc可以重命名Swift暴露给OC的符号名(类名,属性, 函数名等)
4.使用@objcMembers修饰, 默认暴露所有成员
(3) Swift调用C
函数重名, 在Swift中修改C的函数名 @_silgen_name("func_name")
1 | // C函数 |
(4) 相关问题点
1.为什么Swift暴露给OC的类最终要继承自NSObject
oc的方法调用依赖runtime消息传递机制objc_msgSend , 而runtime调用流程依赖类的isa指针
2.Swift调用OC方法底层如何实现? 反过来呢?
(1)Swift调用OC类的方法走的OC的runtime消息机制;
(2)OC调用Swift依然走的OC的runtime消息机制, 默认生成的 <target>-Swift.h, 已经转换成OC代码
(3)需要注意的是纯Swift方法调用走的是虚表(同c++)
二. Swift中的String类型
(1) String的常用操作
1 | var str = "1_2" |
Substring注意
1. Substring发生修改或者强转为String[即String(Substring类型)], 会重新分配新的内存存储字符串数据
2. Substring 和 base共享字符串数据
(2) String 和 character
1 | // c即为 character类型 |
(3) String 相关协议说明
BidirectionalCollection 协议
startIndex, endIndex属性; index方法
RangeReplaceableCollection协议
append, insert, remove 方法
String, Array都遵守以上两个协议, Dict , Set没有遵守; 但是也有类似方法的实现
(4) String 和 NSString
1 | import Foundation |
注意
(1)String 和NSString可以互相桥接转换; as强转是有代价的, 在编译底层其实是生成了桥接的, 只是这种转换在性能上可以忽略
(2)String不能桥接转换成 NSMutableString, 但是NSMutableString可以转换成String; 此处OC的数据类型: 字符串,数组,字典,集合都有此特性.
//!!!!: 注意 可以使用NSMutable...初始化方法转换
(3)字符串比较 都可以使用 == 运算符, 只不过NSString的本质还是调用了isEqual方法而已
三. 协议
(1) 设置协议只能被class继承
常用方案有3种:
protocol Runnable1: AnyObject {}
protocol Runnable2: class {}
@objc protocol Runnable3 {}
且被@objc修饰的协议还可以暴露给OC去遵守实现
1 | protocol Runnable1: AnyObject {} |
(2) 设置可选协议
Swift默认协议方法必须实现, 设置可选
常用方案有2种:
1. 添加扩展协议, 内部实现
extension protocol Runnable1 {
run()
}
2. 借助关键字 @objc optional
@objc protocol Runnable1 {
@objc optional func run()
}
四. KVO/KVC
Swift支持KVO/KVC的条件
1.属性所在的类, 监听器最终继承自NSObject
2.用 @objc dynamic 修饰对应的属性
1 | // KVO 在Swift中的Block方式 |
五. 关联属性
1.在Swift中, class才可以使用关联对象
2.默认情况下, extension不可以扩展存储属性, 但是计算属性(本质是方法),方法除外
3.借助关联对象, 可以实现extension为class增加存储属性的效果
1 | import Foundation |
六. 资源名管理方案
1 | import UIKit |
七. 多线程 (首选GCD)
(1) 子线程->主线程
1 | // #1 |
(2) 延时操作
1 | let time = DispatchTime.now() + 3 |
(3) 单例
1 | // Swift中gcd没有单例方式,可以采用其他方案 |
(4) 锁
1 | // 1.信号量 |
补充
Swift和OC区别
Swift | Objective-C | |
---|---|---|
语言特性 | 静态语言, 更安全 | 动态语言, 不那么安全 |
语法 | 更精简 | 冗长 |
泛型/元组/高阶函数 | 有 | 无 |
命名空间 | 有 | 无 |
方法调用 | 直接调用, 函数表调用, 消息转发 | 消息转发 |
语言效率 | 性能更高,速度更快 | 略低 |
文件特性 | .swift单文件 | .h/.m包含头文件 |
编程特性 | 可以更好的实现函数式编程/响应式编程 | 面向对象编程 |
支持重载 | 支持 | 不支持 |
枚举 | 支持任意类型 | 只支持Int类型 |
id类型和AnyObject
1 | OC中id类型被Swift调用时会自动转成AnyObject,他们很相似,但却其实概念并不一致。 |
参考文章
- 本文作者: 醉疏狂
- 本文链接: https://hubin97.github.io/2020/05/04/OC到Swift小结/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!