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

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)
主站蜘蛛池模板: 新田县| 马龙县| 开阳县| 休宁县| 南阳市| 瑞昌市| 桐庐县| 文成县| 屏东市| 南岸区| 宁武县| 祥云县| 漠河县| 东源县| 洪江市| 正宁县| 广昌县| 洪泽县| 林芝县| 芦溪县| 雷山县| 礼泉县| 教育| 尤溪县| 大方县| 陇西县| 嘉义市| 本溪| 安达市| 五大连池市| 勐海县| 缙云县| 永安市| 延寿县| 襄汾县| 天门市| 如皋市| 繁峙县| 新巴尔虎左旗| 马尔康县| 深圳市|