【问题标题】:Converting Dictionary Key type in Swift 5 with Dictionary(uniqueKeysWithValues:)使用 Dictionary(uniqueKeysWithValues:) 在 Swift 5 中转换字典键类型
【发布时间】:2020-07-26 12:33:43
【问题描述】:

我正在使用 Alamofire 5 为 iOS 13.4(Swift 5、Xcode 11)编写一个具有网络功能的应用程序。我创建了我的自定义类型 typealias KeyedParameters = [ParameterKeys: Any] 以便能够以“快速”的方式使用我的 API 参数键(即.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"
    ...
}

错误的样子:

【问题讨论】:

  • 我也尝试过字符串插值 ("($0.key.rawValue)")、显式构造函数调用 (String($0.key.rawValue)) 和强制类型转换 ($0.key.rawValue as !String) — 也没有用。

标签: ios swift xcode alamofire swift5


【解决方案1】:

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

您的扩展名KeyedParameterstypealias 代表[ParameterKeys: Any])实际上相当于:

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) })
    }
}

【讨论】:

  • @Alexander:您认为这是编译器中的错误吗?在我看来,它应该可以正常工作,或者这实际上是语言的书面限制?
  • @Rengers 我不确定。我建议你在 Swift 论坛上提问
【解决方案2】:

你最好像这样明确地突出显示类型:

extension KeyedParameters {
    var parameters: Parameters {
        return Parameters(uniqueKeysWithValues:
            self.map { (key, value) in (key.rawValue, value) }
        )
    }
}

为我工作。

【讨论】:

    猜你喜欢
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多