简体   繁体   中英

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

I'm using a JSON API that represents a birthday as three separate values in a dictionary. Since the date has to be added to a dictionary in several places in the same way, I wanted to move the code to a Dictionary extension.

    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 ....

This works just fine. However in a Dictionary extension, I can't seem to get the types right.

    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 `_?`
            }
        }
    }

I also tried casting self with if let self = self as? [String: AnyObject] if let self = self as? [String: AnyObject] without success.

Restricting the Dictionary to only Int values, fails because Int is a non-protocol type. IntegerType didn't work either.

extension Dictionary where Key: StringLiteralConvertible , Value: Int

But I want to add other types of values to the same dictionary, so just having Int s doesn't do it for me.

Casting to Value was the right idea. But it needs to be an optional as? Value as? Value .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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