无法传递不可变的值作为inout参数:文字不可变,为什么? [英] Cannot pass immutable value as inout argument: literals are not mutable, why?

查看:1174
本文介绍了无法传递不可变的值作为inout参数:文字不可变,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个交换2个变量的函数!但对于新的swift,我不能使用'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)


解决方案



使用两个变量: var i = 5
var j = 8
swapF(a:& i,with:& j)

此外,使用最后一个Swift 3快照之一,inout应放置在类型附近,函数的原型变为:

  func swapF(a:inout Int,b:inout Int)


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)

解决方案

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 ) 

这篇关于无法传递不可变的值作为inout参数:文字不可变,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆