ios - 如何为 Swift Dictionary 可变扩展获取正确的类型以添加​​具有不同键的 Int 值

标签 ios swift swift2

我正在使用一个 JSON API,它将生日表示为字典中的三个独立值。由于必须以相同的方式在多个位置将日期添加到字典中,因此我想将代码移动到 Dictionary 扩展中。

    var dict = [String: AnyObject]()
    // other keys are set ....
    if let birthDate = birthDate,
        let calendar = NSCalendar(calendarIdentifier:  NSCalendarIdentifierGregorian) {
        let dateComponents = calendar.components([.Day, .Month, .Year], fromDate: birthDate)
        dict["birthDay"] = dateComponents.day
        dict["birthMonth"] = dateComponents.month
        dict["birthDay"] = dateComponents.year
    }
    // other keys are set ....

这很好用。但是在 Dictionary 扩展中,我似乎无法获得正确的类型。

    extension Dictionary where Key: StringLiteralConvertible , Value: AnyObject {
        // other type restrictions for Key and Value didn't work
        mutating func addBirthDate(birthDay: NSDate?) {
            if let birthDate = birthDay,
                let calendar = NSCalendar(calendarIdentifier:  NSCalendarIdentifierGregorian) {
                let dateComponents = calendar.components([.Day, .Month, .Year], fromDate: birthDate)
                self["birthDay"] = dateComponents.day
                // Cannot assign value of type 'Int' to type `_?`
                self["birthMonth"] = dateComponents.month as Value
                // 'Int' is not convertible to `Value`; did you mean to use 'as!' to force downcast?
                self["birthDay"] = dateComponents.year as NSNumber
                // Cannot assign value of type `NSNumber` to type `_?`
            }
        }
    }

我还尝试使用 if let self = self as? [String: AnyObject] 没有成功。

Dictionary 限制为仅 Int 值失败,因为 Int 是非协议(protocol)类型。 IntegerType 也不起作用。

extension Dictionary where Key: StringLiteralConvertible , Value: Int

但我想将其他类型的值添加到同一个字典中,所以仅使用 Int 对我来说并不能做到这一点。

最佳答案

转换为 Value 是正确的想法。但它必须是可选的 吗?值

if let day = dateComponents.day as? Value {
    self["birthDay"] = day
}

关于ios - 如何为 Swift Dictionary 可变扩展获取正确的类型以添加​​具有不同键的 Int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37207788/

相关文章:

ios - 如何调查 ios 中的内存泄漏?

ios - 启动时的欢迎屏幕

ios - 在 watchOS2 上只有声音和触觉的 Lo​​calNotification

ios - 渐变色 swift

ios - UIButton 上需要单击和双击事件吗?

python - Swift NSSocket 编程/python 教程修复

ios - 有没有办法通过按钮操作将用户发送到设置中的推送通知部分?

ios - 使用Apple LLVM 4.1构建iOS应用时出错

ios - 如何在arkit的scnview中添加自定义UIView?

sprite-kit - 将图像分配给 SKShapeNode 作为球 - Spritekit 游戏