Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot pass immutable value as inout argument: literals are not mutable, why?

I want make a function to swap 2 variables! but for new swift, I can't use 'var' ....

import UIKit

func swapF(inout a:Int, inout with b:Int ) {
    print(" x = \(a) and y = \(b)")
    (a, b) = (b, a)

    print("New x = \(a) and new y = \(b)")
}

swapF(&5, with: &8)
like image 974
S At Avatar asked Jul 10 '16 19:07

S At


1 Answers

Literals cannot be passed as inout parameters since they are intrinsically immutable.

Use two variables instead:

var i=5
var j=8
swapF(a:&i, with: &j)

Furthermore, with one of the last Swift 3 snapshots, inout should be placed near the type, the prototype of your function becomes:

func swapF(a:inout Int, with b:inout Int ) 
like image 172
uraimo Avatar answered Oct 21 '22 01:10

uraimo