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
是为我不会做。