gpt4 book ai didi

ios - 使用 Dictionary(uniqueKeysWithValues :)) 转换 Swift 5 中的字典键类型

转载 作者:行者123 更新时间:2023-12-02 04:14:30 25 4
gpt4 key购买 nike

我正在使用 Alamofire 5 为 iOS 13.4(Swift 5、Xcode 11)编写一个具有网络功能的应用程序。我创建了自定义类型 typealias KeyedParameters = [ParameterKeys: Any]能够以“快速”的方式使用我的 API 参数 key (即 .login 而不是 KeyedParameters.login.rawValue )。

问题是当我尝试将此类型转换回默认 Alamofire 的 Parameters 时,我收到以下错误:Cannot convert return expression of type 'Dictionary<ParameterKeys, Any>' to return type 'Parameters' (aka 'Dictionary<String, Any>')

选角:

extension KeyedParameters {
var parameters: Parameters {
Dictionary(uniqueKeysWithValues: map { ($0.key.rawValue, $0.value) })
}
}

参数键:

enum ParameterKeys: String {
// MARK: - Auth and User
case id, login, password, email, name
case createdAt = "created_at"
...
}

错误看起来如何:

enter image description here

最佳答案

我认为这可能只是一个错误消息的情况。

您的扩展KeyedParameters([ParameterKeys: Any]typealias)实际上相当于:

extension Dictionary where Key == ParameterKeys, Value: Any { ...

在类型本身的声明中调用泛型类型的初始值设定项时,Swift 会出现一些奇怪的行为。如果泛型类型不同,它将无法正确处理。

这是一个更简单的示例,没有太多红鲱鱼(类型别名、枚举原始值等)和依赖项:

extension Dictionary  {
func returnADifferentDict() -> [Character: String] {
let words = [
"apple", "anchovies",
"bacon", "beer",
"celery"
]

return Dictionary(uniqueKeysWithValues:
words.map { ($0.first!, $0) }
)

// fixed:
// return Dictionary<Character, String>(uniqueKeysWithValues:
// words.map { ($0.first!, $0) }
// )

}
}

解决方案是显式指定要初始化的泛型类型的泛型类型参数。就你而言,

extension KeyedParameters {
var parameters: Parameters {
Dictionary<String, Any>(uniqueKeysWithValues: map { ($0.key.rawValue, $0.value) })
}
}

关于ios - 使用 Dictionary(uniqueKeysWithValues :)) 转换 Swift 5 中的字典键类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61196552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com