Swift In-Out Options - Use

I recently learned about the "In-Out" options in Swift, and I have a question for you.

What is a use case when the "In-Out" parameters are better than ex func returning the value you can assign to var?

Thank you for your help.

+4
source share
1 answer

I think a good use case for parameters inoutis the function swapTwoIntsprovided by Swift for programming .

func​ ​swapTwoInts​(​inout​ ​a​: ​Int​, ​inout​ ​b​: ​Int​) {
​    ​let​ ​temporaryA​ = ​a
​    ​a​ = ​b
​    ​b​ = ​temporaryA
​}

Considering

var a = 0
var b = 1

you can easily call

swapTwoInt(&a, b: &b)

Scenario 2: no inout parameters

On the other hand, without parameters, the inoutfunction should be written as follows (more compactly)

func swapTwoInt(a: Int, b: Int) -> (a:Int, b:Int) {
    return (a:b, b:a)
}

3 1:

let swapped = swapTwoInt(a, b: b)
a = swapped.a // was swapped.b, fixed as suggested by Martin R
b = swapped.b

, 2 . , , , .

+1

Source: https://habr.com/ru/post/1618399/


All Articles