2016-05-13 22 views
0

我使用的JSON API代表生日作为字典中的三个单独的值。由于日期必须以相同的方式添加到字典中的几个地方,因此我想将代码移至Dictionary扩展名。如何获取Swift Dictionary可变扩展的类型以便使用不同的键添加Int值

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没有成功。

Dictionary限制为只有Int值,因为Int是非协议类型而失败。 IntegerType也没有工作。

extension Dictionary where Key: StringLiteralConvertible , Value: Int 

但我想其他类型的值添加到字典一样,所以只是有Int是为我不会做。

回答

1

铸造到Value是正确的想法。但它必须是可选的as? Value

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