在Swift语言中,“&"号是什么意思?

编程入门 行业动态 更新时间:2024-10-05 19:16:40
本文介绍了在Swift语言中,“&"号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对&符号的了解只是一点点的了解,但有时我会在变量名的前面看到它.将&放在变量前面会做什么?

I know about the ampersand as a bit operation but sometimes I see it in front of variable names. What does putting an & in front of variables do?

推荐答案

它作为inout来使变量成为输入输出参数.从内到外实际上是指按参考值传递值,而不是按值传递值.而且,它不仅需要通过引用来接受值,还需要通过引用来传递值,因此必须通过&传递. -foo(&myVar)而不只是foo(myVar)

It works as an inout to make the variable an in-out parameter. In-out means in fact passing value by reference, not by value. And it requires not only to accept value by reference, by also to pass it by reference, so pass it with & - foo(&myVar) instead of just foo(myVar)

如您所见,您可以在Swift的错误处理中使用它,您必须创建一个错误引用并将其使用&传递给函数,如果发生错误,该函数将填充错误值,或者将变量传递回给是以前

As you see you can use that in error handing in Swift where you have to create an error reference and pass it to the function using & the function will populate the error value if an error occur or pass the variable back as it was before

为什么要使用它?有时一个函数已经返回了其他值,而仅仅返回另一个值(如错误)会造成混淆,因此我们将其作为inout传递.其他时候,我们希望这些值由函数填充,因此我们不必遍历很多返回值,因为该函数已经为我们做到了-除其他可能的用途外.

Why do we use it? Sometimes a function already returns other values and just returning another one (like an error) would be confusing, so we pass it as an inout. Other times we want the values to be populated by the function so we don't have to iterate over lots of return values, since the function already did it for us - among other possible uses.

希望对您有所帮助!

更多推荐

在Swift语言中,“&"号是什么意思?

本文发布于:2023-11-26 19:06:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634819.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语言   Swift   quot   amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!