【问题标题】:Swift 3 cannot converted argument of type .. to expected argument type "inout _"Swift 3 无法将 .. 类型的参数转换为预期的参数类型“inout _”
【发布时间】:2017-02-13 03:38:24
【问题描述】:

它只是将我的小型 Swift 项目转换为 Swift 3。

这是一个我不明白的编译器错误:

var onLoadedClosures: [() -> ()] = []
open func onLoaded(closure: () -> ()) {
    onLoadedClosures += [closure]
}

无法将“[() -> ()]”类型的值转换为预期的参数类型“inout _”。

我添加了 inout 关键字:

    open func onLoaded(closure: inout () -> ()) {
        onLoadedClosures += [closure]
    }

然后就可以了。但是为什么向数组添加元素需要 inout 关键字呢?虽然我知道 inout 是什么意思。

【问题讨论】:

    标签: swift swift3


    【解决方案1】:

    这是一个令人困惑的错误消息——问题是您需要将 closure: 参数标记为 @escaping 以允许它逃脱函数 onLoaded(closure:) 的生命周期(根据 SE-0103,闭包函数参数现在默认是非转义的)。

    var onLoadedClosures: [() -> ()] = []
    open func onLoaded(closure: @escaping () -> ()) {
        onLoadedClosures += [closure]
    }
    

    当您将参数标记为inout 时它起作用的原因是因为inout 闭包按定义转义(因为它们的值在函数退出时被写回调用者)。但是在这种情况下,根本不需要inout 参数。

    有关 @escaping 的更多信息,请参阅有关更改的 the Swift evolution proposal 以及 this relevant Q&A

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      相关资源
      最近更新 更多