繁体   English   中英

如何正确使用Swift Dictionary可变扩展的类型以使用不同的键添加Int值

[英]How to get the types right for Swift Dictionary mutable extension to add Int values with different keys

我正在使用一个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]我也尝试使用铸造self if let self = self as? [String: AnyObject] if let self = self as? [String: AnyObject]没有成功。

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

extension Dictionary where Key: StringLiteralConvertible , Value: Int

但是我想将其他类型的值添加到同一字典中,因此仅使用Int不会对我有用。

铸造Value是正确的想法。 但是它需要是可选as? Value as? Value

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM