Is there a way to determine if a variable passed in is reference type or value type?

后端 未结 2 1330
走了就别回头了
走了就别回头了 2021-01-03 08:54

In Swift, is there a way to determine through code if a variable passed in is reference type or value type?

For example, is tuple a value type or reference type?

2条回答
  •  耶瑟儿~
    2021-01-03 09:46

    Everything is a value type except for:

    • An instance of a class

    • A function

    • An array (which works in an odd way; it is passed by reference but can become unbound from its other avatars if it is mutable and the number of items is changed)

    The simple code way to test is just to assign to two different var names, change one, and see if they are still equal. For example:

        var tuple1 = (1,2)
        var tuple2 = tuple1
        tuple1.1 = 3
        println(tuple1)
        println(tuple2)
    

    They are different, proving that a tuple is passed by value. But:

        var arr1 = [1,2]
        var arr2 = arr1
        arr1[1] = 3
        println(arr1)
        println(arr2)
    

    They are the same, proving that an array is passed by reference.

    EDIT:

    But in beta 3 of Swift, this unusual behavior of Array is withdrawn, and only class instances and functions are passed by reference. Everything else is passed by value now.

提交回复
热议问题