In-Out Parameters inout keyword
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:
When the function is called, the value of the argument is copied.
In the body of the function, the copy is modified.
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.
func someFunction(a: inout Int) -> () -> Int {return { [a] in return a + 1 }}
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.
func multithreadedFunction(queue: DispatchQueue, x: inout Int) {// Make a local copy and manually copy it back.var localX = xdefer { x = localX }// Operate on localX asynchronously, then wait before returning.queue.async { someMutatingOperation(&localX) }queue.sync {}}
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:
func swapTwoInts(_ a: inout Int, _ b: inout Int) {let temporaryA = aa = bb = temporaryA}
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:
var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")// 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的更多相关文章
- testng参数化及用例排序
http://blog.sina.com.cn/s/blog_6966650401012ra0.html 一.一个简单的测试谷歌搜索 import org.testng.annotations.Tes ...
- 请求Url返回数据较大,使结果分页获取
首先创建了一个单元测试,如下项目视图: 分页结果映射类PageResult的编写: using System; using System.Collections.Generic; using Syst ...
- 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( ...
- skopt超参数优化实例
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_boston from skl ...
- WebDriver+TestNG的一个典型例子
想让测试更加灵活,1. 可以配置使用任意支持的浏览器进行测试:2. 配置所有Google的URL:3. 配置搜索的关键字.修改后的代码: public class GoogleTest { WebDr ...
- swift的值类型和引用类型
前言 最近在学设计模式中,发现 Swift 中的 struct,class 以及 enum 在一般的使用中能够做到互相替换,因此探究其背后的逻辑就十分有必要.而这一问题又引出了 Swift 中的值类型 ...
- MapServer教程2
第二章 Tutorial 教程 MapServer Tutorial MapServer教程 Tutorial background 教程背景 Section 1: Static Maps and t ...
- Odoo Documentation : Environment
Environment The Environment stores various contextual data(上下文数据 ) used by the ORM: the database cur ...
- Elixir's keyword lists as option parameters
备注: 文章转自:https://www.djm.org.uk/posts/writing-extensible-elixir-with-behaviours-adapters-pluggable-b ...
随机推荐
- vue中的slot理解和使用
最近被vue 搞得一塌糊涂,理解的比较慢,工作进度进度要求太快,需求理解不明,造成了很大的压力. 在理解Vue中的Slot的时候看了网上的相关内容,看了半天没看到明白说的是什么,然后自己就安装了vue ...
- mysql查询昨天 一周前 一月前 一年前的数据
mysql 昨天 一周前 一月前 一年前的数据 这里主要用到了DATE_SUB, 参考如下 代码如下: SELECT * FROM yh_contentwhere inputtime>DATE_ ...
- jre1.6下载地址
官方下载地址http://java.sun.com/javase/downloads/widget/jdk6.jsp
- C#--in逆变-out协变
MSDN上的解释 协变保留兼容性,逆变与之相反 in的使用 个人理解:就是表明泛型就是可以逆变的(逆变就是大变小) // Contravariant interface. interface ICon ...
- magento 在全站或者某页面增加外联js或者css的方法
1,在整站末尾增加外联资源 找到当前主题的布局文件cms.xml,在<default></default>添加如下代码: <reference name="be ...
- 搭建单机CDH环境,并更新spark环境
搭建单机CDH环境,并更新spark环境 1,安装VMWare Player,http://dlsw.baidu.com/sw-search-sp/soft/90/13927/VMware_playe ...
- 使用URL在线语音合成
近期一直在做手机的项目,用到了语音合成与识别的功能.就找了几个网址做了分析,这里只实现了内容的合成.并不包括语音识别. 首先看一下谷歌的语音合成地址: http://translate.google. ...
- Java Collection框架—List\ set \map 的异同世界
Java集合是多个对象的容方法.集合(容方法).简单点,事实上就是一个对象,能将具有同样性质的多个元素汇聚成一个总体. Collections Framwork是用来表现和操纵集合的一个统一的体系结构 ...
- FZU 1851 组合数
给你两个数n和m,然后让你求组合数C(n,m)中的质因子的个数. 这里用到的一个定理:判断阶乘n!中的质因子 i 的个数的方法---f(n!)=n/i+n/i^2+n/i^3+.....n/i^m ( ...
- git的经常使用命令
$ git config --global user.name "姓名" $ git config --global user.email "xxx@qq.com&quo ...