我正在使用一个 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/