作为 inout 参数的不可变值

Immutable value as inout argument

我想要一个指针作为 class 的参数。但是当我尝试对 init 进行编码时,我遇到了这个错误:Cannot pass immutable value of type 'AnyObject?' as inout argument

class MyClass {
    var valuePointer: UnsafeMutablePointer<AnyObject?>

    init(value: inout AnyObject?) {
        self.valuePointer = &value
    }
}

我想创建一些 MyClass 的实例,它们都可以引用同一个 "value"。然后,当我在这个 class 中编辑这个值时,它会在其他地方发生变化。

这是我第一次在 Swift 中使用指针。我想我做错了...

您可以在初始化对象时发送指针:

class MyClass {
    var valuePointer: UnsafeMutablePointer<AnyObject?>

    init(value: inout UnsafeMutablePointer<AnyObject?>) {
        self.valuePointer = value
    }
}

在初始化的时候加上指针引用即可MyClass:

let obj = MyClass(value: &obj2)

对于出现cannot pass immutable value as inout argument错误的人。首先检查您的参数是否不是可选的。 Inout 类型似乎不喜欢可选值。

对我来说,我有一个 class 变量定义如下:

// file MyClass.swift

class MyClass{

    var myVariable:SomeClass!

    var otherVariable:OtherClass!

    ...

    func someFunction(){
        otherVariable.delegateFunction(parameter: &myVariable) // error
    }
}

// file OtherClass.swift
class OtherClass{
    func delegateFunction(parameter: inout myVariable){
        // modify myVariable's data members 
    }
}

调用的错误是:

Cannot pass immutable value as inout argument: 'self' is immutable

然后我将 MyClass.swift 中的变量声明更改为不再有!而不是最初指向 class 的某个虚拟实例。

var myVariable:SomeClass = SomeClass() 

然后我的代码就能够按预期进行编译和 运行。所以...以某种方式拥有!在 class 变量上阻止您将该变量作为 inout 变量传递。我不懂为什么。

有人遇到了和我一样的问题:

Cannot pass immutable value as inout argument: implicit conversion from '' to '' requires a temporary

代码如下:

protocol FooProtocol {
    var a: String{get set}
}

class Foo: FooProtocol {
    var a: String
    init(a: String) {
        self.a = a
    }
}

func update(foo: inout FooProtocol) {
    foo.a = "new string"
}

var f = Foo(a: "First String")
update(foo: &f)//Error: Cannot pass immutable value as inout argument: implicit conversion from 'Foo' to 'FooProtocol' requires a temporary

var f = Foo(a: "First String") 更改为 var f: FooProtocol = Foo(a: "First String") 修复了错误。

对我来说,我在这样调用的函数中传递直接值。

    public func testInout(_ a :  inout [Int]) -> Int {
        return a.reduce(0, +) 
    }

testInout(&[1,2,4]) // Getting the error :- Cannot pass immutable value of type '[Int]' as inout argument. Because by default the function parameters are constant.

要消除上述错误,您需要传递具有 var 类型的数组。如下所示。

 var arr = [1, 2, 3] 
   public func testInout(_ a :  inout [Int]) -> Int {
            return a.reduce(0, +) 
        }
    
    testInout(&arr)