加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 将值类型变量传递给函数时如何复制它,该副本是什么?

发布时间:2020-12-14 05:40:01 所属栏目:百科 来源:网络整理
导读:Swift‘s string type is a value type. If you create a new String value,that String value is copied when it is passed to a function or method,or when it is assigned to a constant or variable. 它被分配给常量或变量时被复制,这对我来说很有意义.

Swift‘s string type is a value type. If you create a new String value,that String value is copied when it is passed to a function or method,or when it is assigned to a constant or variable.

它被分配给常量或变量时被复制,这对我来说很有意义.但是当传递给函数的值类型变量也会被复制时,这会让我感到困惑.

将值类型变量传递给函数时如何复制?什么样的“空间”持有这个副本?它是在场景后面无形地创建的某种临时变量,在函数进程被破坏之后?

谢谢

将值类型传递给函数时,请将其视为将其分配给范围为该函数的局部变量,因此复制行为类似于仅分配新的局部变量.

关于复制的位置,我们应该认识到复制行为实际上比听起来更复杂.正如他们在Building Better Apps with Value Types in Swift (WWDC 2015,Session 414)中指出的那样,“副本很便宜”:

Copying a low-level,fundamental type is constant time

  • Int,Double,etc.

Copying a struct,enum,or tuple of value types is constant time

  • CGPoint,etc.

Extensible data structures use copy-on-write

  • Copying involves a fixed number of reference-counting operations

  • String,Array,Set,Dictionary,etc.

关于最后一点,在幕后,Swift做了一些手工操作,避免了每次引用时都复制可扩展的值类型,而只是指向原始引用但跟踪有多少引用,实际上只进行复制( a)写作;其中(b)有多个参考文献.在that video中更详细地讨论了这种行为.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读