与我正在做的相比,是否有更聪明/更正确的方式? 我创建了一个字典,并通过查看每个获取的资产继续枚举和填写年/月/日。
let assetFetchResult = PHAsset.fetchAssetsInAssetCollection(album, options: assetFetchOptions)
if assetFetchResult.count > 0 {
var fetchedAssets = [String:[String:[String:[PHAsset]]]]()
//[year[month[date:arrayOfPhotos]]]
assetFetchResult.enumerateObjectsUsingBlock({
object, index, stop in
let asset:PHAsset = object as! PHAsset
let dateComponents = NSCalendar.currentCalendar().components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: asset.creationDate)
//year group creation
if fetchedAssets["\(dateComponents.year)"] == nil {
fetchedAssets["\(dateComponents.year)"] = [String:[String:[PHAsset]]]()
}
//monthly group creation
if fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"] == nil {
fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"] = [String:[PHAsset]]()
}
//daily group creation
if fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"]!["\(dateComponents.day)"] == nil {
fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"]!["\(dateComponents.day)"] = [PHAsset]()
}
fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"]!["\(dateComponents.day)"]?.append(asset)
})
println(fetchedAssets)
return fetchedAssets
}
答案 0 :(得分:0)
我建议直接使用 Dictionary grouping
,这样更安全和自动管理,如下所述:https://developer.apple.com/documentation/swift/dictionary/3127163-init
这可以是您优化的代码:
let fetchedAssets = Dictionary(grouping: <#assets-array#>) { asset -> DateComponents in
return Calendar.current.dateComponents([.day, .year, .month], from: (asset.creationDate)!)
}
print( fetchedAssets )
您将在控制台中收到如下内容:
(lldb) po fetchedAssets.first
▿ Optional<(key: DateComponents, value: Array<Assets>)>
▿ some : 2 elements
▿ key : year: 2021 month: 5 day: 18 isLeapMonth: false
- year : 2021
- month : 5
- day : 18
- isLeapMonth : false
▿ value : 1 element
▿ 0 : Assets
- asset : <PHAsset: 0x7fcebcc43740> A86BC4A1-63E3-41EB-897D-695A395531D6/L0/001 mediaType=1/4, sourceType=1, (2112x1590), creationDate=2021-05-18 11:19:23 +0000, location=0, hidden=0, favorite=0, adjusted=0
(lldb)