zoukankan      html  css  js  c++  java
  • 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 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的参数传递

        

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

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

        

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

     

  • 相关阅读:
    移动端开发-禁止横屏
    奇葩的对象创建方式(更新中)
    每日积累之8.8
    每日积累 8.6
    折半查找
    linux中的amount的解释
    Redis集群错误
    每日积累 8.6
    Redis中在程序中的应用
    每日积累 8.4
  • 原文地址:https://www.cnblogs.com/doudouyoutang/p/5581360.html
Copyright © 2011-2022 走看看