How can I access `AnyHashable` types in `Any` in Swift?
Asked Answered
D

1

1

I'm using APAddressBook to get the address book from the users phone. it generates the following object of users when I print the variable serializedContacts:

[[
    AnyHashable("name"): {
        compositeName = "Mary Jones";
        firstName = Mary;
        lastName = Jones;
    },
    AnyHashable("recordID"): 111, 
    AnyHashable("phones"): <__NSSingleObjectArrayI 0x17401c160>({
           number = "0411 111 111";
    })
], 
[
    AnyHashable("name"): {
        compositeName = "Jack Smith";
        firstName = Jack;
        lastName = Smith;
    }, 
    AnyHashable("recordID"): 112, 
    AnyHashable("phones"): <__NSSingleObjectArrayI 0x17401c190>({
        number = "0422 222 222";
    })
]]

I can access a single contact by simply printing serializedContacts[0], although how can I access the finer details such as compositeName and number?

I tried serializedContacts[0].name and serializedContacts[0].phones, although receive the error.

Value of type 'Any' has no member 'name'.

Dressingdown answered 5/10, 2016 at 2:6 Comment(0)
K
1

You should also convert the property you're trying to access to AnyHashable before. In your case this is:

serializedContacts[0][AnyHashable("name")]
Koala answered 20/1, 2017 at 16:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.