官术网_书友最值得收藏!

swap versus swapAt

The swap(_:_: ) method in Swift 3 works on "pass by reference principle" and swaps two elements of a given array on the spot. In pass by reference, actual memory addresses are used rather than values:

var integerArray = [1, 2, 4, 3, 5]
swap(integerArray [2], integerArray [3])

As you can see, the parameters are passed as in out parameters, which means the actual references or placeholder addresses are accessible directly inside the function. On the other hand, Swift 4’s swapAt(_:_:) works on “pass by value” principle and only the corresponding indices are passed to the function to be swapped:

integerArray.swapAt(2, 3)

The swap(_:_:) function will not be seen in Swift 4, because it will be deprecated and removed, and you have a couple of approaches to replace it. The first approach uses a temporary constant as follows:

let temp = a
a = b
b = temp

The second takes advantage of Swift's built in tuples, as follows:

(b, a) = (a, b)
主站蜘蛛池模板: 潮安县| 德令哈市| 佳木斯市| 霞浦县| 迁西县| 宁津县| 仁怀市| 双峰县| 新沂市| 陵川县| 子洲县| 丹巴县| 田林县| 景德镇市| 洪洞县| 望谟县| 衢州市| 洛南县| 阜平县| 车致| 富顺县| 济宁市| 福贡县| 西乌珠穆沁旗| 衡水市| 巴东县| 毕节市| 兴业县| 鹤庆县| 西乌珠穆沁旗| 榆中县| 博客| 武乡县| 泽普县| 南江县| 博罗县| 梁平县| 都江堰市| 太白县| 客服| 顺义区|