Невозможно получить значения ключей для возврата в качестве словаря из выборки данных Core в Swift - PullRequest
0 голосов
/ 28 апреля 2020

Я сохраняю некоторые ключевые значения в профиле. Но я пытаюсь получить и вернуть как словарь, чтобы принять в качестве ключевых значений для основного класса.

static func fetchProfile) -> [String: Any]? {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let profileFetch = NSFetchRequest<NSFetchRequestResult>(entityName: AccountinfoKeyConstant.Entity_Profile)
    var fetchedObjects: [String: Any]?

    var entityDescription: NSEntityDescription? = nil
    entityDescription = NSEntityDescription.entity(forEntityName: AccountinfoKeyConstant.Entity_Profile, in: context)
    profileFetch.entity = entityDescription
    do {
        let objects = try context.fetch(profileFetch)
        print("objects \(objects)")
        fetchedObjects = objects as [String: Any]
    } catch let error as NSError {
        print("Could not fetched. \(error), \(error.userInfo)")
    }
    return fetchedObjects

}

В приведенном выше коде я получаю следующую ошибку:

Невозможно преобразовать значение типа '[Any]' для ввода '[String: Any]' в принудительном порядке

для этой строки fetchedObjects = objects as [String: Any]

Есть предложения? Как взять только словарь, чтобы вернуть его в основной класс?

Вывод:

objects [<Profile: 0x6000026c3ca0> (entity: Profile; id: 0x8d815a305b375e8d <x-coredata://F92995FE-578E-48EB-AA07-242ECBBBBFE4/Profile/p20>; data: {
     birthdate = "04/22/2020";
     email = "example@test.com";
    "family_name" = myName;
    gender = " ";
    "given_name" = myName123;
    name = name123;
})]

1 Ответ

1 голос
/ 28 апреля 2020

Чтобы получить словарь, вам нужно указать шаблон c NSFetchRequest как NSFetchRequest<NSDictionary>, а также добавить dictionaryResultType.

Тем не менее выборка объектов возвращает всегда an необязательный массив.

Дальнейшее создание метода throw значительно сокращает код.

static func fetchProfile() -> [[String: Any]] throws {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let profileFetch : NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: AccountinfoKeyConstant.Entity_Profile)
    profileFetch.resultType = .dictionaryResultType

    return try context.fetch(profileFetch) as! [[String:Any]]

}

Если в объекте есть только одна запись, вернуть первый элемент

static func fetchProfile() -> [String: Any] throws {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let profileFetch : NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: AccountinfoKeyConstant.Entity_Profile)
    profileFetch.resultType = .dictionaryResultType
    let result = try context.fetch(profileFetch) as! [[String:Any]]
    return result.first ?? [:]

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...