Home  >  Q&A  >  body text

ios - swift中inout参数传入一个函数,在函数体内print怎么没有被执行?

在一个交换函数中,a和b的值进行交换,使用inout参数传值,这样函数对参数所做的修改将会影响参数本身,但是为什么在swap函数里的print没有被执行?

func swap(inout a : Int , inout b : Int){
    let tmp = a
    print("123")
    a = b
    b = tmp
    
}

var a = 6
var b = 9
print("交换之前,a的值是\(a),b的值是\(b)")
swap(&a, &b)
print("交换之后,a的值是\(a),b的值是\(b)")

输出的结果是:
交换之前,a的值是6,b的值是9
交换之后,a的值是9,b的值是6

swap函数里的print哪里去了???

大家讲道理大家讲道理2716 days ago452

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:54:05

    I was confused when I first read the question.
    I opened a Playground and tried it, only to find out:

    The swap function you called is obviously provided by Swift itself!

    Although you defined a new swap function above.

    So, the solution is to change the function name...


    Let me tell you by the way:
    In Swift, you can exchange two values ​​​​like this

    (a, b) = (b, a)

    reply
    0
  • Cancelreply