首页 > 解决方案 > 为什么我可以在使用 try 时使用 inout 参数改变 let 常量?

问题描述

这将无法编译并出现以下错误:

不可变值“self.constantValue”不得传入输出

class Test {
    let constantValue: String = ""


    init() {
        Test.makeABC(&constantValue)
    }

    static func makeABC(_ string: inout String) {
        string = "ABC"
    }
}

然而,这将编译并实际改变 let 常量。

class Test {
    let constantValue: String = ""


    init() {
        try? Test.makeABC(&constantValue)
    }

    static func makeABC(_ string: inout String) throws {
        string = "ABC"
    }
}

有谁知道为什么会这样以及它是否是预期的行为?

我提交了一个错误https://bugs.swift.org/browse/SR-8368

标签: swiftpointersimmutabilityinout

解决方案


推荐阅读