问题描述
将类或原始类型传递给函数时,函数对参数的任何更改都将反映在类外部.基本上,inout
参数应该执行相同的操作.
When passing a class or primitive type into a function, any change made in the function to the parameter will be reflected outside of the class. This is basically the same thing an inout
parameter is supposed to do.
什么是inout参数的好用例?
What is a good use case for an inout parameter?
推荐答案
inout
意味着修改本地变量也将修改传入的参数.没有它,传入的参数将保持相同的值.尝试在使用inout
时考虑引用类型,而在不使用它的情况下考虑值类型.
inout
means that modifying the local variable will also modify the passed-in parameters. Without it, the passed-in parameters will remain the same value. Trying to think of reference type when you are using inout
and value type without using it.
例如:
import UIKit
var num1: Int = 1
var char1: Character = "a"
func changeNumber(var num: Int) {
num = 2
print(num) // 2
print(num1) // 1
}
changeNumber(num1)
func changeChar(inout char: Character) {
char = "b"
print(char) // b
print(char1) // b
}
changeChar(&char1)
swap
函数将是一个很好的用例,它将修改传入的参数.
A good use case will be swap
function that it will modify the passed-in parameters.
迅速3+注:从Swift 3 开始,inout
关键字必须在 之后且在类型之前.例如,Swift 3+现在需要func changeChar(char: inout Character)
.
Swift 3+ Note: Starting in Swift 3, the inout
keyword must come after the colon and before the type. For example, Swift 3+ now requires func changeChar(char: inout Character)
.
这篇关于什么时候使用inout参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!