【问题标题】:Generic method causes "cannot pass immutable value of type AnyObject? as inout argument"通用方法导致“无法传递 AnyObject 类型的不可变值?作为 inout 参数”
【发布时间】:2016-05-20 01:58:02
【问题描述】:

我正在开发一个钥匙串包装类的 Swift 版本。我有点不明白为什么会这样:

private func executeFetch(query: KeyStoreObject) throws -> AnyObject? {
    var result: AnyObject?
    try executeQuery(query) { SecItemCopyMatching(query.data, &result) }
    return result
}

这不是:

private func executeFetch<T: AnyObject>(query: KeyStoreObject) throws -> T? {
    var result: T?
    try executeQuery(query) { SecItemCopyMatching(query.data, &result) }
    return result
}

【问题讨论】:

    标签: swift generics immutability anyobject


    【解决方案1】:

    我认为错误在于SecItemCopyMatching 可能会尝试将AnyObject 类型的任何东西(即任何东西)分配给result。但是,在第二个示例中,result 不一定是 AnyObject 类型;它是T 的某个特定类型,它是AnyObject 的子类。因此,SecItemCopyMatching 可能无法正确设置result。例如,如果TInt,但SecItemCopyMatching 想将result 设置为String,该怎么办?当resultAnyObject 类型时,这不再是问题。

    【讨论】:

    • 谢谢,有道理,基本上我限制 SecItemCopyMatching 返回任何对象类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多