Search code examples
swiftgenericsimmutabilityanyobject

Generic method causes "cannot pass immutable value of type AnyObject? as inout argument"


I'm working on a Swift version of a Keychain wrapper class. I'm a bit puzzled why this works:

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

And this doesn't:

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

Solution

  • I believe that the error is that SecItemCopyMatching may attempt to assign anything of type AnyObject (i.e. anything at all) to result. However, in the second example result is not necessarily of type AnyObject; it is some particular type T that is a subclass of AnyObject. Thus, SecItemCopyMatching may be unable to correctly set result. For instance, what if T is Int, but SecItemCopyMatching wants to set result to a String? When result is of type AnyObject this is no longer an issue.