You write an in-out parameter by placing the inout keyword right before a parameter’s type. An in-out parameter has a value that is passed in to the function, is modified by the function, and is passed back out of the function to replace the original value.

https://docs.swift.org/swift-book/LanguageGuide/Functions.html

In-Out Parameters

In-out parameters are passed as follows:

  1. When the function is called, the value of the argument is copied.

  2. In the body of the function, the copy is modified.

  3. When the function returns, the copy’s value is assigned to the original argument.

This behavior is known as copy-in copy-out or call by value result. For example, when a computed property or a property with observers is passed as an in-out parameter, its getter is called as part of the function call and its setter is called as part of the function return.

As an optimization, when the argument is a value stored at a physical address in memory, the same memory location is used both inside and outside the function body. The optimized behavior is known as call by reference; it satisfies all of the requirements of the copy-in copy-out model while removing the overhead of copying. Write your code using the model given by copy-in copy-out, without depending on the call-by-reference optimization, so that it behaves correctly with or without the optimization.

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.

For more information about memory safety and memory exclusivity, see Memory Safety.

A closure or nested function that captures an in-out parameter must be nonescaping. If you need to capture an in-out parameter without mutating it or to observe changes made by other code, use a capture list to explicitly capture the parameter immutably.

  1. func someFunction(a: inout Int) -> () -> Int {
  2. return { [a] in return a + 1 }
  3. }

If you need to capture and mutate an in-out parameter, use an explicit local copy, such as in multithreaded code that ensures all mutation has finished before the function returns.

  1. func multithreadedFunction(queue: DispatchQueue, x: inout Int) {
  2. // Make a local copy and manually copy it back.
  3. var localX = x
  4. defer { x = localX }
  5. // Operate on localX asynchronously, then wait before returning.
  6. queue.async { someMutatingOperation(&localX) }
  7. queue.sync {}
  8. }

For more discussion and examples of in-out parameters, see In-Out Parameters.

In-Out Parameters

Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.

You write an in-out parameter by placing the inout keyword right before a parameter’s type. An in-out parameter has a value that is passed in to the function, is modified by the function, and is passed back out of the function to replace the original value. For a detailed discussion of the behavior of in-out parameters and associated compiler optimizations, see In-Out Parameters.

You can only pass a variable as the argument for an in-out parameter. You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified. You place an ampersand (&) directly before a variable’s name when you pass it as an argument to an in-out parameter, to indicate that it can be modified by the function.

NOTE

In-out parameters cannot have default values, and variadic parameters cannot be marked as inout.

Here’s an example of a function called swapTwoInts(_:_:), which has two in-out integer parameters called aand b:

  1. func swapTwoInts(_ a: inout Int, _ b: inout Int) {
  2. let temporaryA = a
  3. a = b
  4. b = temporaryA
  5. }

The swapTwoInts(_:_:) function simply swaps the value of b into a, and the value of a into b. The function performs this swap by storing the value of a in a temporary constant called temporaryA, assigning the value of b to a, and then assigning temporaryA to b.

You can call the swapTwoInts(_:_:) function with two variables of type Int to swap their values. Note that the names of someInt and anotherInt are prefixed with an ampersand when they are passed to the swapTwoInts(_:_:) function:

  1. var someInt = 3
  2. var anotherInt = 107
  3. swapTwoInts(&someInt, &anotherInt)
  4. print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
  5. // Prints "someInt is now 107, and anotherInt is now 3"

The example above shows that the original values of someInt and anotherInt are modified by the swapTwoInts(_:_:) function, even though they were originally defined outside of the function.

NOTE

In-out parameters are not the same as returning a value from a function. The swapTwoInts example above does not define a return type or return a value, but it still modifies the values of someInt and anotherInt. In-out parameters are an alternative way for a function to have an effect outside of the scope of its function body.

In-Out Parameters inout keyword的更多相关文章

  1. testng参数化及用例排序

    http://blog.sina.com.cn/s/blog_6966650401012ra0.html 一.一个简单的测试谷歌搜索 import org.testng.annotations.Tes ...

  2. 请求Url返回数据较大,使结果分页获取

    首先创建了一个单元测试,如下项目视图: 分页结果映射类PageResult的编写: using System; using System.Collections.Generic; using Syst ...

  3. MapServer Tutorial——MapServer7.2.1教程学习——第一节用例实践:Example1.7 Adding a wms layer

    MapServer Tutorial——MapServer7.2.1教程学习——第一节用例实践:Example1.7 Adding a wms layer 前言 Add OGC WMS Layers( ...

  4. skopt超参数优化实例

    import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_boston from skl ...

  5. WebDriver+TestNG的一个典型例子

    想让测试更加灵活,1. 可以配置使用任意支持的浏览器进行测试:2. 配置所有Google的URL:3. 配置搜索的关键字.修改后的代码: public class GoogleTest { WebDr ...

  6. swift的值类型和引用类型

    前言 最近在学设计模式中,发现 Swift 中的 struct,class 以及 enum 在一般的使用中能够做到互相替换,因此探究其背后的逻辑就十分有必要.而这一问题又引出了 Swift 中的值类型 ...

  7. MapServer教程2

    第二章 Tutorial 教程 MapServer Tutorial MapServer教程 Tutorial background 教程背景 Section 1: Static Maps and t ...

  8. Odoo Documentation : Environment

    Environment The Environment stores various contextual data(上下文数据 ) used by the ORM: the database cur ...

  9. Elixir's keyword lists as option parameters

    备注: 文章转自:https://www.djm.org.uk/posts/writing-extensible-elixir-with-behaviours-adapters-pluggable-b ...

随机推荐

  1. js中writeln()方法

    writeln( ) 方法与 write( ) 方法几乎一样,差别仅在于是前者将在所提供的任何字符串后添加一个换行符.在 HTML 中,这通常只会在后面产生一个空格:不过如果使用了 <PRE&g ...

  2. 爬虫系列(十三) 用selenium爬取京东商品

    这篇文章,我们将通过 selenium 模拟用户使用浏览器的行为,爬取京东商品信息,还是先放上最终的效果图: 1.网页分析 (1)初步分析 原本博主打算写一个能够爬取所有商品信息的爬虫,可是在分析过程 ...

  3. 【hihocoder 1476】矩形计数

    [题目链接]:http://hihocoder.com/problemset/problem/1476 [题意] [题解] 首先不考虑黑格子,计算出一共有多少个矩形: 枚举矩形的大小r×c,这样大小的 ...

  4. Orcale用户管理

    类 ------表 对象----行 属性----列 软件开发流程: 需求调研 需求分析 概要分析 详细分析 编码 测试 上线 维护 论坛: 1.注册和登录 2.发帖,回帖(关注,浏览数) 用户:(昵称 ...

  5. 洛谷 P2046 BZOJ 2007 海拔(NOI2010)

    题目描述 YT市是一个规划良好的城市,城市被东西向和南北向的主干道划分为n×n个区域.简单起见,可以将YT市看作 一个正方形,每一个区域也可看作一个正方形.从而,YT城市中包括(n+1)×(n+1)个 ...

  6. 【ACM】hdu_2115_I Love This Game_201308021517

    I Love This GameTime Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)T ...

  7. F - Count the Colors

    F - Count the Colors ZOJ - 1610   思路:调了一个小时,但是发现自己线段树木有写错,颜色统计出了错误.但是不明白自己颜色统计为什么错了. 求大佬指点迷津.思路很简单,就 ...

  8. [React] Capture values using the lifecycle hook getSnapshotBeforeUpdate in React 16.3

    getSnapshotBeforeUpdate is a lifecycle hook that was introduced with React 16.3. It is invoked right ...

  9. 一个使用命令行编译Android项目的工具类

    一个使用命令行编译Android项目的工具类 简单介绍 编译apk项目须要使用的几个工具,基本都在sdk中,它们各自是(Windows系统): 1.aapt.exe 资源打包工具 2.android. ...

  10. win7配置免安装mysql5.6.19过程具体解释

    本文主要介绍免安装配置mysql5.6.19的过程,整个过程中自己出现非常多次失误,经过整理,现将一次可成功的过程记录下来,供大家參考. 准备 在mysq官网 http://dev.mysql.com ...