首页 技术 正文
技术 2022年11月15日
0 收藏 991 点赞 3,454 浏览 1686 个字

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 PropertiesMethodsSubscriptsInitializationExtensions, 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的参数传递

    swift 中Value Type VS Class Type

  2)使用let修饰的值类型,意味着该值不可变,比如数组Array,被修饰之后,数组长度不可变,但是其中的内容还是可变的。

     被let修饰的数组Array在参数传递过程中不会拷贝

    swift 中Value Type VS Class Type

  参考资料:http://blog.human-friendly.com/swift-arrays-the-bugs-the-bad-and-the-ugly-incomplete

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,498
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,911
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,745
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,501
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,139
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,303