[英]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. 我正在使用一个JSON API,它将生日表示为字典中的三个独立值。 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. 由于必须以相同的方式在多个位置将日期添加到字典中,因此我想将代码移到
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 ....
This works just fine. 这样很好。 However in a
Dictionary
extension, I can't seem to get the types right. 但是在
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 `_?`
}
}
}
I also tried casting self
with if let self = self as? [String: AnyObject]
if let self = self as? [String: AnyObject]
我也尝试使用铸造self
if let self = self as? [String: AnyObject]
if let self = self as? [String: AnyObject]
without success. if let self = self as? [String: AnyObject]
没有成功。
Restricting the Dictionary
to only Int
values, fails because Int
is a non-protocol type. 将
Dictionary
限制为仅Int
值失败,因为Int
是非协议类型。 IntegerType
didn't work either. IntegerType
也不起作用。
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. 但是我想将其他类型的值添加到同一字典中,因此仅使用
Int
不会对我有用。
Casting to Value
was the right idea. 铸造
Value
是正确的想法。 But it needs to be an optional as? Value
但是它需要是可选
as? Value
as? Value
. as? Value
。
if let day = dateComponents.day as? Value {
self["birthDay"] = day
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.