ios - 无法将不可变值作为输入参数 : literals are not mutable, 传递,为什么?

标签 ios swift function

我想创建一个函数来交换两个变量!但对于新的 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)

最佳答案

文字不能作为 inout 参数传递,因为它们本质上是不可变的。

使用两个变量:

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

此外,在最后的 Swift 3 快照之一中,inout 应放置在类型附近,函数的原型(prototype)将变为:

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

关于ios - 无法将不可变值作为输入参数 : literals are not mutable, 传递,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54815558/

相关文章:

c++ - 如何为 C++ 函数中的结构分配默认值?

javascript - 在不打开的情况下编写 promise 然后调用

ios - UILabel:自定义下划线颜色?

ios - 为什么字符串格式在 UILabel 中不起作用?

ios - 从 API 响应访问数据是 iOS 应用程序

ios - Firebase 覆盖条目

swift - Collectionview具有多个大小单元格的流程布局

ios - UITableViewCell 中文本的自动滚动动画

ios - 计算路线后绘制的注释移动到用户的位置 - Skobbler

调用实例方法时出现 C++ 访问冲突