ios - Inout 参数不允许互相使用别名

标签 ios swift

如果为两个参数传递相同的变量会出错。 谁能解释为什么我们不能在输入参数函数中传递相同的变量,而我们可以在普通函数中传递

func swapTwoInts(a: inout Int, b: inout Int) {

    print(a)
    print(b)

}

var a = 12    

swapTwoInts(a: &a, b: &a)

最佳答案

来自 Apple Documentation :

Within a function, don’t access a value that was passed as an in-out argument, even if the original value is available in the current scope. Accessing the original is a simultaneous access of the value, which violates Swift’s memory exclusivity guarantee. For the same reason, you can’t pass the same value to multiple in-out parameters.

在您的示例中,您创建了同一变量的 2 个副本。当函数返回时,它们必须被分配给原始参数。这就是这种情况下的冲突。

关于ios - Inout 参数不允许互相使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52362315/

相关文章:

ios - 如何获取显示在 TableView 单元格中的数据并将其显示在文本字段中?

ios - 在使用 swift 的 iOS 中,如何创建一个始终位于整个应用程序顶部的可拖动且 float 的 UIView

arrays - 掉落(其中 : {}) remove(where: {}) function in Swift?

Titanium 应用程序中的 iOS native 功能

ios - 设置 UIScrollView 以在 3 个 View Controller 之间滑动

Swift 常量连接变量来定义 if 语句

ios - 更改 TableView 文本标签类型

android - 无法在android中启动cocos2dx ios项目

ios - Swift 3.0 Xcode8 beta 4 如何修复 Calendar.current.date

ios - Twitter API - iOS