S At S At - 1 year ago 210
iOS Question

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)

Answer Source

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 ) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download