swift 中Value Type VS Class Type
ios 中Value Type 和 Class Type 有哪些异同点,这个问题是在微信的公共帐号中看到的,觉得挺有意思,这里梳理一下。
1、swift 中为什么要设置值类型?
值类型在参数传递、赋值的过程中采用的是Copy的过程,copy的"值"是该值所在的内存块,相比于class类型,copy更直接,没有对象中方法调用(饮用计数、copy方法等),因此效率更高。猜测swift引入的值类型主要是为了提高效率。
2、swift 存在哪些值类型
swift中常见的值类型有 struct, enum, or tuple,常用的 Array, String, and Dictionary 从最开始的引用类型变成了值类型
3、值类型和class类型应该怎样区分选择
如果是简单的小数据集合、或者在多线程中传递使用、或者你想保存多份实例,你可以使用值类型,此外应该使用class类型。
https://developer.apple.com/swift/blog/?id=10
4、值类型和class 有哪些异同点
Classes and structures in Swift have many things in common. Both can:
-
-
Define properties to store values
-
Define methods to provide functionality
-
Define subscripts to provide access to their values using subscript syntax
-
Define initializers to set up their initial state
-
Be extended to expand their functionality beyond a default implementation
-
Conform to protocols to provide standard functionality of a certain kind
-
For more information, see Properties, Methods, Subscripts, Initialization, Extensions, and Protocols.
Classes have additional capabilities that structures do not:
-
-
Inheritance enables one class to inherit the characteristics of another.
-
Type casting enables you to check and interpret the type of a class instance at runtime.
-
Deinitializers enable an instance of a class to free up any resources it has assigned.
-
Reference counting allows more than one reference to a class instance.
-
值类型参数传递方式是copy的过程、class类型的参数传递是传递引用的过程。
局部变量中,值类型的内存分配的是栈内存,class 对象分配的内存在堆上,因此值类型的内存通常分配效率更高
值类型在多线程中因为存在多份拷贝,所以避免了资源竞争的问题
5、swift 中的容器对象是值类型(swift2.0 版本之后),如果是一个大型的Array的对象在参数传递的时候,拷贝它是否会带来效率的降低呢?
值类型在函数参数传递过程中,通常意味着copy的过程,但是在swift中存在下面两种情况不会copy
1)编译器会自动优化,减少不必要copy的参数传递
2)使用let修饰的值类型,意味着该值不可变,比如数组Array,被修饰之后,数组长度不可变,但是其中的内容还是可变的。
被let修饰的数组Array在参数传递过程中不会拷贝
参考资料:http://blog.human-friendly.com/swift-arrays-the-bugs-the-bad-and-the-ugly-incomplete
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架