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

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)
主站蜘蛛池模板: 读书| 荥经县| 开鲁县| 汤原县| 万山特区| 焦作市| 游戏| 翁源县| 乐亭县| 嘉鱼县| 同心县| 鄂尔多斯市| 汽车| 定州市| 云阳县| 盘山县| 嵊泗县| 济宁市| 贞丰县| 新竹县| 东丰县| 镶黄旗| 永新县| 平舆县| 五莲县| 都昌县| 武穴市| 平远县| 泽普县| 三原县| 西乡县| 博罗县| 灌云县| 油尖旺区| 民乐县| 日照市| 波密县| 兴国县| 宣武区| 永昌县| 临沂市|