0

我正在开发一个钥匙串包装类的 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
}
4

1 回答 1

0

我相信错误在于SecItemCopyMatching可能会尝试将任何类型的东西AnyObject(即任何东西)分配给result. 但是,在第二个示例result中不一定是 type AnyObject;它是某种特定类型T,它是AnyObject. 因此,SecItemCopyMatching可能无法正确设置result。例如, if Tis Int,但SecItemCopyMatching想设置result为 aString怎么办?何时result是类型,AnyObject这不再是问题。

于 2016-05-20T03:02:12.673 回答