为什么我们不能通过引用 swift 中的 inout 函数来传递 const 值?
Why can't we pass const values by reference to inout functions in swift?
在 C 中,虽然我们将值声明为 const int a = 5;
,但我们可以将 &a
传递给声明为 void someFun(const int *);
.
的函数
作为一个rule of thumb,在C中,当原值不需要改变时, i) 如果对象的大小小于或等于指针的大小,我们按值传递, ii) 否则我们通过 const 引用传递它,将整个值复制到函数将占用更多资源。
但是在swift中,即使函数中没有修改inout参数,我们也不能将声明为let a = 5
的值传递给声明为someFun(_ z: inout Int) -> ()
的函数。因此我们必须在函数中将 z 标记为 let。这会将整个值复制到函数中。如果 a 类型的大小很大,这可能会花费更多。有解决办法吗?
据我了解,
The 'inout' in swift does not actually send the reference of
the property to the function. When you change the value of the
property passed as 'inout', the swift on its own end checks if you
have changed the value and then performs that change to the actual
property on its own. So the only thing 'inout' does in swift is
changing the value of the actual property. So even if it allows you to send a constant as
'inout', you still won't be able to make any use of it, because of the very nature of the 'constant'. You just cant change the value of a 'constant', because its immutable.
参考Link:https://docs.swift.org/swift-book/LanguageGuide/Functions.html
编辑:
正如@SouravKannanthaB 在上面的评论中提到的,swift 可以通过模仿引用传递的行为来自动优化 inout,但我不相信有人可以强制进行优化。
在 C 中,虽然我们将值声明为 const int a = 5;
,但我们可以将 &a
传递给声明为 void someFun(const int *);
.
作为一个rule of thumb,在C中,当原值不需要改变时, i) 如果对象的大小小于或等于指针的大小,我们按值传递, ii) 否则我们通过 const 引用传递它,将整个值复制到函数将占用更多资源。
但是在swift中,即使函数中没有修改inout参数,我们也不能将声明为let a = 5
的值传递给声明为someFun(_ z: inout Int) -> ()
的函数。因此我们必须在函数中将 z 标记为 let。这会将整个值复制到函数中。如果 a 类型的大小很大,这可能会花费更多。有解决办法吗?
据我了解,
The 'inout' in swift does not actually send the reference of the property to the function. When you change the value of the property passed as 'inout', the swift on its own end checks if you have changed the value and then performs that change to the actual property on its own. So the only thing 'inout' does in swift is changing the value of the actual property. So even if it allows you to send a constant as 'inout', you still won't be able to make any use of it, because of the very nature of the 'constant'. You just cant change the value of a 'constant', because its immutable.
参考Link:https://docs.swift.org/swift-book/LanguageGuide/Functions.html
编辑: 正如@SouravKannanthaB 在上面的评论中提到的,swift 可以通过模仿引用传递的行为来自动优化 inout,但我不相信有人可以强制进行优化。