[英]How to get the types right for Swift Dictionary mutable extension to add Int values with different keys
我正在使用一個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]
我也嘗試使用鑄造self
if let self = self as? [String: AnyObject]
if let self = self as? [String: AnyObject]
沒有成功。
將Dictionary
限制為僅Int
值失敗,因為Int
是非協議類型。 IntegerType
也不起作用。
extension Dictionary where Key: StringLiteralConvertible , Value: Int
但是我想將其他類型的值添加到同一字典中,因此僅使用Int
不會對我有用。
鑄造Value
是正確的想法。 但是它需要是可選as? Value
as? Value
。
if let day = dateComponents.day as? Value {
self["birthDay"] = day
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.